RouteBuilder
in package
Provides features for building routes inside scopes.
Gives an easy to use way to build routes and append them into a route collection.
Table of Contents
Constants
- ID = '[0-9]+'
- Regular expression for auto increment IDs
- UUID = '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}'
- Regular expression for UUIDs
Properties
- $_collection : RouteCollection
- The route collection routes should be added to.
- $_extensions : array<string|int, string>
- The extensions that should be set into the routes connected.
- $_namePrefix : string
- Name prefix for connected routes.
- $_params : array<string|int, mixed>
- The scope parameters if there are any.
- $_path : string
- The path prefix scope that this collection uses.
- $_resourceMap : array<string, array<string|int, mixed>>
- Default HTTP request method => controller action map.
- $_routeClass : string
- Default route class to use if none is provided in connect() options.
- $middleware : array<string|int, string>
- The list of middleware that routes in this builder get added during construction.
Methods
- __construct() : mixed
- Constructor
- addExtensions() : $this
- Add additional extensions to what is already in current scope
- applyMiddleware() : $this
- Apply one or many middleware to the current route scope.
- connect() : Route
- Connects a new Route.
- delete() : Route
- Create a route that only responds to DELETE requests.
- fallbacks() : $this
- Connect the `/{controller}` and `/{controller}/{action}/*` fallback routes.
- get() : Route
- Create a route that only responds to GET requests.
- getExtensions() : array<string|int, string>
- Get the extensions in this route builder's scope.
- getMiddleware() : array<string|int, mixed>
- Get the middleware that this builder will apply to routes.
- getRouteClass() : string
- Get default route class.
- head() : Route
- Create a route that only responds to HEAD requests.
- loadPlugin() : $this
- Load routes from a plugin.
- middlewareGroup() : $this
- Apply a set of middleware to a group
- nameExists() : bool
- Checks if there is already a route with a given name.
- namePrefix() : string
- Get/set the name prefix for this scope.
- options() : Route
- Create a route that only responds to OPTIONS requests.
- params() : array<string|int, mixed>
- Get the parameter names/values for this scope.
- patch() : Route
- Create a route that only responds to PATCH requests.
- path() : string
- Get the path this scope is for.
- plugin() : $this
- Add plugin routes.
- post() : Route
- Create a route that only responds to POST requests.
- prefix() : $this
- Add prefixed routes.
- put() : Route
- Create a route that only responds to PUT requests.
- redirect() : Route|RedirectRoute
- Connects a new redirection Route in the router.
- registerMiddleware() : $this
- Register a middleware with the RouteCollection.
- resources() : $this
- Generate REST resource routes for the given controller(s).
- scope() : $this
- Create a new routing scope.
- setExtensions() : $this
- Set the extensions in this route builder's scope.
- setRouteClass() : $this
- Set default route class.
- _makeRoute() : Route
- Create a route object, or return the provided object.
- _methodRoute() : Route
- Helper to create routes that only respond to a single HTTP method.
- parseDefaults() : array<string|int, mixed>
- Parse the defaults if they're a string
Constants
ID
Regular expression for auto increment IDs
public
string
ID
= '[0-9]+'
UUID
Regular expression for UUIDs
public
string
UUID
= '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}'
Properties
$_collection
The route collection routes should be added to.
protected
RouteCollection
$_collection
$_extensions
The extensions that should be set into the routes connected.
protected
array<string|int, string>
$_extensions
= []
$_namePrefix
Name prefix for connected routes.
protected
string
$_namePrefix
= ''
$_params
The scope parameters if there are any.
protected
array<string|int, mixed>
$_params
$_path
The path prefix scope that this collection uses.
protected
string
$_path
$_resourceMap
Default HTTP request method => controller action map.
protected
static array<string, array<string|int, mixed>>
$_resourceMap
= ['index' => ['action' => 'index', 'method' => 'GET', 'path' => ''], 'create' => ['action' => 'add', 'method' => 'POST', 'path' => ''], 'view' => ['action' => 'view', 'method' => 'GET', 'path' => '{id}'], 'update' => ['action' => 'edit', 'method' => ['PUT', 'PATCH'], 'path' => '{id}'], 'delete' => ['action' => 'delete', 'method' => 'DELETE', 'path' => '{id}']]
$_routeClass
Default route class to use if none is provided in connect() options.
protected
string
$_routeClass
= \Cake\Routing\Route\Route::class
$middleware
The list of middleware that routes in this builder get added during construction.
protected
array<string|int, string>
$middleware
= []
Methods
__construct()
Constructor
public
__construct(RouteCollection $collection, string $path[, array<string|int, mixed> $params = [] ][, array<string, mixed> $options = [] ]) : mixed
Options
-
routeClass
- The default route class to use when adding routes. -
extensions
- The extensions to connect when adding routes. -
namePrefix
- The prefix to prepend to all route names. -
middleware
- The names of the middleware routes should have applied.
Parameters
- $collection : RouteCollection
-
The route collection to append routes into.
- $path : string
-
The path prefix the scope is for.
- $params : array<string|int, mixed> = []
-
The scope's routing parameters.
- $options : array<string, mixed> = []
-
Options list.
addExtensions()
Add additional extensions to what is already in current scope
public
addExtensions(array<string|int, string>|string $extensions) : $this
Parameters
- $extensions : array<string|int, string>|string
-
One or more extensions to add
Return values
$thisapplyMiddleware()
Apply one or many middleware to the current route scope.
public
applyMiddleware(string ...$names) : $this
Requires middleware to be registered via registerMiddleware()
.
Parameters
- $names : string
-
The names of the middleware to apply to the current scope.
Tags
Return values
$thisconnect()
Connects a new Route.
public
connect(Route|string $route[, array<string|int, mixed>|string $defaults = [] ][, array<string, mixed> $options = [] ]) : Route
Routes are a way of connecting request URLs to objects in your application. At their core routes are a set or regular expressions that are used to match requests to destinations.
Examples:
$routes->connect('/{controller}/{action}/*');
The first parameter will be used as a controller name while the second is
used as the action name. The '/*' syntax makes this route greedy in that
it will match requests like /posts/index
as well as requests
like /posts/edit/1/foo/bar
.
$routes->connect('/home-page', ['controller' => 'Pages', 'action' => 'display', 'home']);
The above shows the use of route parameter defaults. And providing routing parameters for a static route.
$routes->connect(
'/{lang}/{controller}/{action}/{id}',
[],
['id' => '[0-9]+', 'lang' => '[a-z]{3}']
);
Shows connecting a route with custom route parameters as well as providing patterns for those parameters. Patterns for routing parameters do not need capturing groups, as one will be added for each route params.
$options offers several 'special' keys that have special meaning in the $options array.
-
routeClass
is used to extend and change how individual routes parse requests and handle reverse routing, via a custom routing class. Ex.'routeClass' => 'SlugRoute'
-
pass
is used to define which of the routed parameters should be shifted into the pass array. Adding a parameter to pass will remove it from the regular route array. Ex.'pass' => ['slug']
. -
persist
is used to define which route parameters should be automatically included when generating new URLs. You can override persistent parameters by redefining them in a URL or remove them by setting the parameter tofalse
. Ex.'persist' => ['lang']
-
multibytePattern
Set to true to enable multibyte pattern support in route parameter patterns. -
_name
is used to define a specific name for routes. This can be used to optimize reverse routing lookups. If undefined a name will be generated for each connected route. -
_ext
is an array of filename extensions that will be parsed out of the url if present. See . -
_method
Only match requests with specific HTTP verbs. -
_host
- Define the host name pattern if you want this route to only match specific host names. You can use.*
and to create wildcard subdomains/hosts e.g.*.example.com
matches all subdomains onexample.com
. - '_port` - Define the port if you want this route to only match specific port number.
Example of using the _method
condition:
$routes->connect('/tasks', ['controller' => 'Tasks', 'action' => 'index', '_method' => 'GET']);
The above route will only be matched for GET requests. POST requests will fail to match this route.
Parameters
- $route : Route|string
-
A string describing the template of the route
- $defaults : array<string|int, mixed>|string = []
-
An array describing the default route parameters. These parameters will be used by default and can supply routing parameters that are not dynamic. See above.
- $options : array<string, mixed> = []
-
An array matching the named elements in the route to regular expressions which that element should match. Also contains additional parameters such as which routed parameters should be shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a custom routing class.
Tags
Return values
Routedelete()
Create a route that only responds to DELETE requests.
public
delete(string $template, array<string|int, mixed>|string $target[, string|null $name = null ]) : Route
Parameters
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null = null
-
The name of the route.
Return values
Routefallbacks()
Connect the `/{controller}` and `/{controller}/{action}/*` fallback routes.
public
fallbacks([string|null $routeClass = null ]) : $this
This is a shortcut method for connecting fallback routes in a given scope.
Parameters
- $routeClass : string|null = null
-
the route class to use, uses the default routeClass if not specified
Return values
$thisget()
Create a route that only responds to GET requests.
public
get(string $template, array<string|int, mixed>|string $target[, string|null $name = null ]) : Route
Parameters
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null = null
-
The name of the route.
Return values
RoutegetExtensions()
Get the extensions in this route builder's scope.
public
getExtensions() : array<string|int, string>
Return values
array<string|int, string>getMiddleware()
Get the middleware that this builder will apply to routes.
public
getMiddleware() : array<string|int, mixed>
Return values
array<string|int, mixed>getRouteClass()
Get default route class.
public
getRouteClass() : string
Return values
stringhead()
Create a route that only responds to HEAD requests.
public
head(string $template, array<string|int, mixed>|string $target[, string|null $name = null ]) : Route
Parameters
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null = null
-
The name of the route.
Return values
RouteloadPlugin()
Load routes from a plugin.
public
loadPlugin(string $name) : $this
The routes file will have a local variable named $routes
made available which contains
the current RouteBuilder instance.
Parameters
- $name : string
-
The plugin name
Tags
Return values
$thismiddlewareGroup()
Apply a set of middleware to a group
public
middlewareGroup(string $name, array<string|int, string> $middlewareNames) : $this
Parameters
- $name : string
-
Name of the middleware group
- $middlewareNames : array<string|int, string>
-
Names of the middleware
Return values
$thisnameExists()
Checks if there is already a route with a given name.
public
nameExists(string $name) : bool
Parameters
- $name : string
-
Name.
Return values
boolnamePrefix()
Get/set the name prefix for this scope.
public
namePrefix([string|null $value = null ]) : string
Modifying the name prefix will only change the prefix used for routes connected after the prefix is changed.
Parameters
- $value : string|null = null
-
Either the value to set or null.
Return values
stringoptions()
Create a route that only responds to OPTIONS requests.
public
options(string $template, array<string|int, mixed>|string $target[, string|null $name = null ]) : Route
Parameters
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null = null
-
The name of the route.
Return values
Routeparams()
Get the parameter names/values for this scope.
public
params() : array<string|int, mixed>
Return values
array<string|int, mixed>patch()
Create a route that only responds to PATCH requests.
public
patch(string $template, array<string|int, mixed>|string $target[, string|null $name = null ]) : Route
Parameters
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null = null
-
The name of the route.
Return values
Routepath()
Get the path this scope is for.
public
path() : string
Return values
stringplugin()
Add plugin routes.
public
plugin(string $name[, callable|array<string|int, mixed> $options = [] ][, callable|null $callback = null ]) : $this
This method creates a new scoped route collection that includes relevant plugin information.
The plugin name will be inflected to the underscore version to create
the routing path. If you want a custom path name, use the path
option.
Routes connected in the scoped collection will have the correct path segment prepended, and have a matching plugin routing key set.
Options
-
path
The path prefix to use. Defaults toInflector::dasherize($name)
. -
_namePrefix
Set a prefix used for named routes. The prefix is prepended to the name of any route created in a scope callback.
Parameters
- $name : string
-
The plugin name to build routes for
- $options : callable|array<string|int, mixed> = []
-
Either the options to use, or a callback to build routes.
- $callback : callable|null = null
-
The callback to invoke that builds the plugin routes Only required when $options is defined.
Return values
$thispost()
Create a route that only responds to POST requests.
public
post(string $template, array<string|int, mixed>|string $target[, string|null $name = null ]) : Route
Parameters
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null = null
-
The name of the route.
Return values
Routeprefix()
Add prefixed routes.
public
prefix(string $name[, callable|array<string|int, mixed> $params = [] ][, callable|null $callback = null ]) : $this
This method creates a scoped route collection that includes relevant prefix information.
The $name parameter is used to generate the routing parameter name.
For example a path of admin
would result in 'prefix' => 'admin'
being
applied to all connected routes.
You can re-open a prefix as many times as necessary, as well as nest prefixes.
Nested prefixes will result in prefix values like admin/api
which translates
to the Controller\Admin\Api\
namespace.
If you need to have prefix with dots, eg: '/api/v1.0', use 'path' key for $params argument:
$route->prefix('Api', function($route) {
$route->prefix('V10', ['path' => '/v1.0'], function($route) {
// Translates to `Controller\Api\V10\` namespace
});
});
Parameters
- $name : string
-
The prefix name to use.
- $params : callable|array<string|int, mixed> = []
-
An array of routing defaults to add to each connected route. If you have no parameters, this argument can be a callable.
- $callback : callable|null = null
-
The callback to invoke that builds the prefixed routes.
Tags
Return values
$thisput()
Create a route that only responds to PUT requests.
public
put(string $template, array<string|int, mixed>|string $target[, string|null $name = null ]) : Route
Parameters
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null = null
-
The name of the route.
Return values
Routeredirect()
Connects a new redirection Route in the router.
public
redirect(string $route, array<string|int, mixed>|string $url[, array<string, mixed> $options = [] ]) : Route|RedirectRoute
Redirection routes are different from normal routes as they perform an actual header redirection if a match is found. The redirection can occur within your application or redirect to an outside location.
Examples:
$routes->redirect('/home/*', ['controller' => 'Posts', 'action' => 'view']);
Redirects /home/* to /posts/view and passes the parameters to /posts/view. Using an array as the redirect destination allows you to use other routes to define where a URL string should be redirected to.
$routes->redirect('/posts/*', 'http://google.com', ['status' => 302]);
Redirects /posts/* to http://google.com with a HTTP status of 302
Options:
-
status
Sets the HTTP status (default 301) -
persist
Passes the params to the redirected route, if it can. This is useful with greedy routes, routes that end in*
are greedy. As you can remap URLs and not lose any passed args.
Parameters
- $route : string
-
A string describing the template of the route
- $url : array<string|int, mixed>|string
-
A URL to redirect to. Can be a string or a Cake array-based URL
- $options : array<string, mixed> = []
-
An array matching the named elements in the route to regular expressions which that element should match. Also contains additional parameters such as which routed parameters should be shifted into the passed arguments. As well as supplying patterns for routing parameters.
Return values
Route|RedirectRouteregisterMiddleware()
Register a middleware with the RouteCollection.
public
registerMiddleware(string $name, MiddlewareInterface|Closure|string $middleware) : $this
Once middleware has been registered, it can be applied to the current routing scope or any child scopes that share the same RouteCollection.
Parameters
- $name : string
-
The name of the middleware. Used when applying middleware to a scope.
- $middleware : MiddlewareInterface|Closure|string
-
The middleware to register.
Tags
Return values
$thisresources()
Generate REST resource routes for the given controller(s).
public
resources(string $name[, callable|array<string|int, mixed> $options = [] ][, callable|null $callback = null ]) : $this
A quick way to generate a default routes to a set of REST resources (controller(s)).
Usage
Connect resource routes for an app controller:
$routes->resources('Posts');
Connect resource routes for the Comments controller in the Comments plugin:
Router::plugin('Comments', function ($routes) {
$routes->resources('Comments');
});
Plugins will create lowercase dasherized resource routes. e.g
/comments/comments
Connect resource routes for the Articles controller in the Admin prefix:
Router::prefix('Admin', function ($routes) {
$routes->resources('Articles');
});
Prefixes will create lowercase dasherized resource routes. e.g
/admin/posts
You can create nested resources by passing a callback in:
$routes->resources('Articles', function ($routes) {
$routes->resources('Comments');
});
The above would generate both resource routes for /articles
, and /articles/{article_id}/comments
.
You can use the map
option to connect additional resource methods:
$routes->resources('Articles', [
'map' => ['deleteAll' => ['action' => 'deleteAll', 'method' => 'DELETE']]
]);
In addition to the default routes, this would also connect a route for /articles/delete_all
.
By default, the path segment will match the key name. You can use the 'path' key inside the resource
definition to customize the path name.
You can use the inflect
option to change how path segments are generated:
$routes->resources('PaymentTypes', ['inflect' => 'underscore']);
Will generate routes like /payment-types
instead of /payment_types
Options:
- 'id' - The regular expression fragment to use when matching IDs. By default, matches integer values and UUIDs.
- 'inflect' - Choose the inflection method used on the resource name. Defaults to 'dasherize'.
- 'only' - Only connect the specific list of actions.
- 'actions' - Override the method names used for connecting actions.
- 'map' - Additional resource routes that should be connected. If you define 'only' and 'map', make sure that your mapped methods are also in the 'only' list.
- 'prefix' - Define a routing prefix for the resource controller. If the current scope defines a prefix, this prefix will be appended to it.
- 'connectOptions' - Custom options for connecting the routes.
- 'path' - Change the path so it doesn't match the resource name. E.g ArticlesController
is available at
/posts
Parameters
- $name : string
-
A controller name to connect resource routes for.
- $options : callable|array<string|int, mixed> = []
-
Options to use when generating REST routes, or a callback.
- $callback : callable|null = null
-
An optional callback to be executed in a nested scope. Nested scopes inherit the existing path and 'id' parameter.
Return values
$thisscope()
Create a new routing scope.
public
scope(string $path, callable|array<string|int, mixed> $params[, callable|null $callback = null ]) : $this
Scopes created with this method will inherit the properties of the scope they are added to. This means that both the current path and parameters will be appended to the supplied parameters.
Special Keys in $params
-
_namePrefix
Set a prefix used for named routes. The prefix is prepended to the name of any route created in a scope callback.
Parameters
- $path : string
-
The path to create a scope for.
- $params : callable|array<string|int, mixed>
-
Either the parameters to add to routes, or a callback.
- $callback : callable|null = null
-
The callback to invoke that builds the plugin routes. Only required when $params is defined.
Tags
Return values
$thissetExtensions()
Set the extensions in this route builder's scope.
public
setExtensions(array<string|int, string>|string $extensions) : $this
Future routes connected in through this builder will have the connected extensions applied. However, setting extensions does not modify existing routes.
Parameters
- $extensions : array<string|int, string>|string
-
The extensions to set.
Return values
$thissetRouteClass()
Set default route class.
public
setRouteClass(string $routeClass) : $this
Parameters
- $routeClass : string
-
Class name.
Return values
$this_makeRoute()
Create a route object, or return the provided object.
protected
_makeRoute(Route|string $route, array<string|int, mixed> $defaults, array<string, mixed> $options) : Route
Parameters
- $route : Route|string
-
The route template or route object.
- $defaults : array<string|int, mixed>
-
Default parameters.
- $options : array<string, mixed>
-
Additional options parameters.
Tags
Return values
Route_methodRoute()
Helper to create routes that only respond to a single HTTP method.
protected
_methodRoute(string $method, string $template, array<string|int, mixed>|string $target, string|null $name) : Route
Parameters
- $method : string
-
The HTTP method name to match.
- $template : string
-
The URL template to use.
- $target : array<string|int, mixed>|string
-
An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to.
- $name : string|null
-
The name of the route.
Return values
RouteparseDefaults()
Parse the defaults if they're a string
protected
parseDefaults(array<string|int, mixed>|string $defaults) : array<string|int, mixed>
Parameters
- $defaults : array<string|int, mixed>|string
-
Defaults array from the connect() method.