Parses the request URL into controller, action, and parameters. Uses the connected routes to match the incoming URL string to parameters that will allow the request to be dispatched. Also handles converting parameter lists into URL strings, using the connected routes. Routing allows you to decouple the way the world interacts with your application (URLs) and the implementation (controllers and actions).
Connecting routes is done using Router::connect(). When parsing incoming requests or reverse matching parameters, routes are enumerated in the order they were connected. You can modify the order of connected routes using Router::promote(). For more information on routes and how to connect them see Router::connect().
Named parameters allow you to embed key:value pairs into path segments. This allows you create hash structures using URLs. You can define how named parameters work in your application using Router::connectNamed()
_handleNoRoute( array $url )
A special fallback method that handles URL arrays that cannot match any defined routes.
$url
string
Router::url()
_parseExtension( string $url )
Parses a file extension out of a URL, if Router::parseExtensions() is enabled.
$url
array
_validateRouteClass( string $routeClass )
Validates that the passed route class exists and is a subclass of CakeRoute
$routeClass
string
RouterException
connect( string $route , array $defaults array() , array $options array() )
Connects a new Route in the router.
Routes are a way of connecting request URLs to objects in your application. At their core routes are a set of regular expressions that are used to match requests to destinations.
Examples:
Router::connect('/:controller/:action/*');
The first token ':controller' 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
.
Router::connect('/home-page', array('controller' => 'pages', 'action' => 'display', 'home'));
The above shows the use of route parameter defaults, and providing routing parameters for a static route.
Router::connect( '/:lang/:controller/:action/:id', array(), array('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.
$defaults is merged with the results of parsing the request URL to form the final routing destination and its parameters. This destination is expressed as an associative array by Router. See the output of Router::parse()
.
$options offers four 'special' keys. pass
, named
, persist
and routeClass
have special meaning in the $options array.
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' => array('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 to false
. Ex. 'persist' => array('lang')
routeClass
is used to extend and change how individual routes parse requests and handle reverse routing, via a custom routing class. Ex. 'routeClass' => 'SlugRoute'
named
is used to configure named parameters at the route level. This key uses the same options as Router::connectNamed()You can also add additional conditions for matching routes to the $defaults array. The following conditions can be used:
[type]
Only match requests for specific content types.[method]
Only match requests with specific HTTP verbs.[server]
Only match when $_SERVER['SERVER_NAME'] matches the given value.Example of using the [method]
condition:
Router::connect('/tasks', array('controller' => 'tasks', 'action' => 'index', '[method]' => 'GET'));
The above route will only be matched for GET requests. POST requests will fail to match this route.
$route
$defaults
optional array() $options
optional array() array
RouterException
Router::$routes
connectNamed( array $named , array $options array() )
Specifies what named parameters CakePHP should be parsing out of incoming URLs. By default CakePHP will parse every named parameter out of incoming URLs. However, if you want to take more control over how named parameters are parsed you can use one of the following setups:
Do not parse any named parameters:
Router::connectNamed(false);
Parse only default parameters used for CakePHP's pagination:
Router::connectNamed(false, array('default' => true));
Parse only the page parameter if its value is a number:
Router::connectNamed(array('page' => '[\d]+'), array('default' => false, 'greedy' => false));
Parse only the page parameter no matter what.
Router::connectNamed(array('page'), array('default' => false, 'greedy' => false));
Parse only the page parameter if the current action is 'index'.
Router::connectNamed( array('page' => array('action' => 'index')), array('default' => false, 'greedy' => false) );
Parse only the page parameter if the current action is 'index' and the controller is 'pages'.
Router::connectNamed( array('page' => array('action' => 'index', 'controller' => 'pages')), array('default' => false, 'greedy' => false) );
greedy
Setting this to true will make Router parse all named params. Setting it to false will parse only the connected named params.default
Set this to true to merge in the default set of named parameters.reset
Set to true to clear existing rules and start fresh.separator
Change the string used to separate the key & value in a named parameter. Defaults to :
$named
$options
optional array() array
currentRoute( )
Returns the route matching the current request (useful for requestAction traces)
CakeRoute
defaultRouteClass( string $routeClass null )
Set the default route class to use or return the current one
$routeClass
optional null string|null
RouterException
extensions( )
Get the list of extensions that can be parsed by Router.
To initially set extensions use Router::parseExtensions()
To add more see setExtensions()
array
fullBaseUrl( string $base null )
Sets the full base URL that will be used as a prefix for generating fully qualified URLs for this application. If no parameters are passed, the currently configured value is returned.
If you change the configuration value `App.fullBaseUrl
` during runtime and expect the router to produce links using the new setting, you are required to call this method passing such value again.
$base
optional null `http://example.com
`string
getNamedExpressions( )
Gets the named route elements for use in app/Config/routes.php
array
Router::$_namedExpressions
getParam( string $name 'controller' , boolean $current false )
Gets URL parameter by name
$name
optional 'controller' $current
optional false string|null
getParams( boolean $current false )
Gets parameter information
$current
optional false array
getPaths( boolean $current false )
Gets path information
$current
optional false array
getRequest( boolean $current false )
Gets the current request object, or the first one.
$current
optional false CakeRequest|null
mapResources( string|array $controller , array $options array() )
Creates REST resource routes for the given controller(s). When creating resource routes for a plugin, by default the prefix will be changed to the lower_underscore version of the plugin name. By providing a prefix you can override this behavior.
$controller
$options
optional array() array
namedConfig( )
Gets the current named parameter configuration values.
array
Router::$_namedConfig
normalize( array|string $url '/' )
Normalizes a URL for purposes of comparison.
Will strip the base path off and replace any double /'s. It will not unify the casing and underscoring of the input value.
$url
optional '/' string
parse( string $url )
Parses given URL string. Returns 'routing' parameters for that URL.
$url
array
parseExtensions( )
Instructs the router to parse out file extensions from the URL.
For example, http://example.com/posts.rss would yield a file extension of "rss". The file extension itself is made available in the controller as $this->params['ext']
, and is used by the RequestHandler component to automatically switch to alternate layouts and templates, and load helpers corresponding to the given content, i.e. RssHelper. Switching layouts and helpers requires that the chosen extension has a defined mime type in CakeResponse
A list of valid extension can be passed to this method, i.e. Router::parseExtensions('rss', 'xml'); If no parameters are given, anything after the first . (dot) after the last / in the URL will be parsed, excluding querystring parameters (i.e. ?q=...).
popRequest( )
Pops a request off of the request stack. Used when doing requestAction
CakeRequest
Router::setRequestInfo()
Object::requestAction()
prefixes( )
Returns the list of prefixes used in connected routes
array
promote( integer $which null )
Promote a route (by default, the last one added) to the beginning of the list
$which
optional null boolean
queryString( string|array $q , array $extra array() , boolean $escape false )
Generates a well-formed querystring from $q
$q
$extra
optional array() $escape
optional false array
redirect( string $route , array $url , array $options array() )
Connects a new redirection Route in the router.
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:
Router::redirect('/home/*', array('controller' => 'posts', 'action' => 'view'), array('persist' => true));
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.
Router::redirect('/posts/*', 'http://google.com', array('status' => 302));
Redirects /posts/* to http://google.com with a HTTP status of 302
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 loose any passed/named args.$route
$url
$options
optional array() array
Router::$routes
reload( )
Reloads default Router settings. Resets all class variables and removes all connected routes.
requestRoute( )
Returns the route matching the current request URL.
CakeRoute
resourceMap( array $resourceMap null )
Resource map getter & setter.
$resourceMap
optional null mixed
Router::$_resourceMap
reverse( CakeRequest|array $params , boolean $full false )
Reverses a parsed parameter array into a string.
Works similarly to Router::url(), but since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys. Those keys need to be specially handled in order to reverse a params array into a string URL.
This will strip out 'autoRender', 'bare', 'requested', and 'return' param names as those are used for CakePHP internals and should not normally be part of an output URL.
CakeRequest
|array $params
$full
optional false string
setExtensions( array $extensions , boolean $merge true )
Set/add valid extensions.
To have the extensions parsed you still need to call Router::parseExtensions()
$extensions
$merge
optional true array
setRequestInfo( CakeRequest|array $request )
Takes parameter and path information back from the Dispatcher, sets these parameters as the current request parameters that are merged with URL arrays created later in the request.
Nested requests will create a stack of requests. You can remove requests using Router::popRequest(). This is done automatically when using Object::requestAction().
Will accept either a CakeRequest object or an array of arrays. Support for accepting arrays may be removed in the future.
CakeRequest
|array $request
stripPlugin( string $base , string $plugin null )
Removes the plugin name from the base URL.
$base
$plugin
optional null string
url( string|array $url null , boolean|array $full false )
Finds URL for specified action.
Returns a URL pointing to a combination of controller and action. Param $url can be:
There are a few 'special' parameters that can change the final URL string that is generated
base
- Set to false to remove the base path from the generated URL. If your application is not in the root directory, this can be used to generate URLs that are 'cake relative'. cake relative URLs are required when using requestAction.?
- Takes an array of query string parameters#
- Allows you to set URL hash fragments.full_base
- If true the Router::fullBaseUrl()
value will be prepended to generated URLs.$url
optional null $full
optional false string
string | ACTION Regular expression for action names | 'index|show|add|create|edit|update|remove|del|delete|view|item' |
string | DAY Regular expression for days | '0[1-9]|[12][0-9]|3[01]' |
string | ID Regular expression for auto increment IDs | '[0-9]+' |
string | MONTH Regular expression for months | '0[1-9]|1[012]' |
string | UUID Regular expression for UUIDs | '[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}' |
string | YEAR Regular expression for years | '[12][0-9]{3}' |
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.7/class-Router.html