Class Router
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
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
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()
Copyright: Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Location: Cake/Routing/Router.php
Constants summary
Properties summary
-
$_currentRoute
protected staticarray
The route matching the URL of the current request -
$_initialState
protected staticarray
Initial state is populated the first time reload() is called which is at the bottom of this file. This is a cheat as get_class_vars() returns the value of static vars even if they have changed.
-
$_namedConfig
protected staticstring
Stores all information necessary to decide what named arguments are parsed under what conditions. -
$_namedExpressions
protected staticarray
Named expressions -
$_parseExtensions
protected staticboolean
Directive for Router to parse out file extensions for mapping to Content-types. -
$_prefixes
protected staticarray
List of action prefixes used in connected routes. Includes admin prefix
-
$_requests
protected staticarray
Maintains the request object stack for the current request. This will contain more than one request object when requestAction is used.
-
$_resourceMap
protected staticarray
Default HTTP request method => controller action map. -
$_resourceMapped
protected staticarray
List of resource-mapped controllers -
$_routeClass
protected staticstring
Default route class to use -
$_validExtensions
protected staticarray
List of valid extensions to parse from a URL. If null, any extension is allowed. -
$routes
public staticarray
Array of routes connected with Router::connect()
Method Summary
-
_handleNoRoute() protected static
A special fallback method that handles url arrays that cannot match any defined routes.
-
_parseExtension() protected static
Parses a file extension out of a URL, if Router::parseExtensions() is enabled. -
_setPrefixes() protected static
Sets the Routing prefixes. -
_validateRouteClass() protected static
Validates that the passed route class exists and is a subclass of CakeRoute -
connect() public static
Connects a new Route in the router. -
connectNamed() public static
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:
-
currentRoute() public static
Returns the route matching the current request (useful for requestAction traces) -
defaultRouteClass() public static
Set the default route class to use or return the current one -
extensions() public static
Get the list of extensions that can be parsed by Router. To add more extensions use Router::parseExtensions()
-
getNamedExpressions() public static
Gets the named route elements for use in app/Config/routes.php -
getParam() public static
Gets URL parameter by name -
getParams() public static
Gets parameter information -
getPaths() public static
Gets path information -
getRequest() public static
Get the either the current request object, or the first one. -
mapResources() public static
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.
-
namedConfig() public static
Gets the current named parameter configuration values. -
normalize() public static
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.
-
parse() public static
Parses given URL string. Returns 'routing' parameters for that url. -
parseExtensions() public static
Instructs the router to parse out file extensions from the URL. For example, http://example.com/posts.rss would yield an 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 inCakeResponse
-
popRequest() public static
Pops a request off of the request stack. Used when doing requestAction -
prefixes() public static
Returns the list of prefixes used in connected routes -
promote() public static
Promote a route (by default, the last one added) to the beginning of the list -
queryString() public static
Generates a well-formed querystring from $q -
redirect() public static
Connects a new redirection Route in the router. -
reload() public static
Reloads default Router settings. Resets all class variables and removes all connected routes.
-
requestRoute() public static
Returns the route matching the current request URL. -
resourceMap() public static
Resource map getter & setter. -
reverse() public static
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.
-
setRequestInfo() public static
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.
-
stripPlugin() public static
Removes the plugin name from the base URL. -
url() public static
Finds URL for specified action.
Method Detail
_handleNoRoute() protected static ¶
_handleNoRoute( array $url )
A special fallback method that handles url arrays that cannot match any defined routes.
Parameters
- array $url
- A url that didn't match any routes
Returns
A generated url for the array
See
_parseExtension() protected static ¶
_parseExtension( string $url )
Parses a file extension out of a URL, if Router::parseExtensions() is enabled.
Parameters
- string $url
Returns
Returns an array containing the altered URL and the parsed extension.
_validateRouteClass() protected static ¶
_validateRouteClass( $routeClass )
Validates that the passed route class exists and is a subclass of CakeRoute
Parameters
- $routeClass
Returns
Throws
connect() public static ¶
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 or regular expressions that are used to match requests to destinations.
Examples:
Router::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
.
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.
$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()
Parameters
- string $route
- A string describing the template of the route
- array $defaults optional array()
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.
- array $options optional array()
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.
Returns
Array of routes
Throws
See
connectNamed() public static ¶
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) ); }}}
Options
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:
Parameters
- array $named
A list of named parameters. Key value pairs are accepted where values are either regex strings to match, or arrays as seen above.
- array $options optional array()
- Allows to control all settings: separator, greedy, reset, default
Returns
currentRoute() public static ¶
currentRoute( )
Returns the route matching the current request (useful for requestAction traces)
Returns
defaultRouteClass() public static ¶
defaultRouteClass( string $routeClass = null )
Set the default route class to use or return the current one
Parameters
- string $routeClass optional null
- to set as default
Returns
void|string
Throws
extensions() public static ¶
extensions( )
Get the list of extensions that can be parsed by Router. To add more extensions use Router::parseExtensions()
Returns
Array of extensions Router is configured to parse.
getNamedExpressions() public static ¶
getNamedExpressions( )
Gets the named route elements for use in app/Config/routes.php
Returns
Named route elements
See
getParam() public static ¶
getParam( string $name = 'controller' , boolean $current = false )
Gets URL parameter by name
Parameters
- string $name optional 'controller'
- Parameter name
- boolean $current optional false
- Current parameter, useful when using requestAction
Returns
Parameter value
getParams() public static ¶
getParams( boolean $current = false )
Gets parameter information
Parameters
- boolean $current optional false
- Get current request parameter, useful when using requestAction
Returns
Parameter information
getPaths() public static ¶
getPaths( boolean $current = false )
Gets path information
Parameters
- boolean $current optional false
- Current parameter, useful when using requestAction
Returns
getRequest() public static ¶
getRequest( boolean $current = false )
Get the either the current request object, or the first one.
Parameters
- boolean $current optional false
- Whether you want the request from the top of the stack or the first one.
Returns
mapResources() public static ¶
mapResources( mixed $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.
Options:
- 'id' - The regular expression fragment to use when matching IDs. By default, matches integer values and UUIDs.
- 'prefix' - URL prefix to use for the generated routes. Defaults to '/'.
Parameters
- mixed $controller
- A controller name or array of controller names (i.e. "Posts" or "ListItems")
- array $options optional array()
- Options to use when generating REST routes
Returns
Array of mapped resources
namedConfig() public static ¶
namedConfig( )
Gets the current named parameter configuration values.
Returns
See
normalize() public static ¶
normalize( mixed $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.
Parameters
- mixed $url optional '/'
- URL to normalize Either an array or a string url.
Returns
Normalized URL
parse() public static ¶
parse( string $url )
Parses given URL string. Returns 'routing' parameters for that url.
Parameters
- string $url
- URL to be parsed
Returns
Parsed elements from URL
parseExtensions() public static ¶
parseExtensions( )
Instructs the router to parse out file extensions from the URL. For example,
http://example.com/posts.rss would yield an 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=...).
See
popRequest() public static ¶
popRequest( )
Pops a request off of the request stack. Used when doing requestAction
Returns
See
Object::requestAction()
prefixes() public static ¶
prefixes( )
Returns the list of prefixes used in connected routes
Returns
A list of prefixes used in connected routes
promote() public static ¶
promote( integer $which = null )
Promote a route (by default, the last one added) to the beginning of the list
Parameters
- integer $which optional null
A zero-based array index representing the route to move. For example, if 3 routes have been added, the last route would be 2.
Returns
Returns false if no route exists at the position specified by $which.
queryString() public static ¶
queryString( string|array $q , array $extra = array() , boolean $escape = false )
Generates a well-formed querystring from $q
Parameters
- string|array $q
Query string Either a string of already compiled query string arguments or an array of arguments to convert into a query string.
- array $extra optional array()
- Extra querystring parameters.
- boolean $escape optional false
- Whether or not to use escaped &
Returns
redirect() public static ¶
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
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 loose any passed/named args.
Parameters
- string $route
- A string describing the template of the route
- array $url
- A url to redirect to. Can be a string or a Cake array-based url
- array $options optional array()
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.
Returns
Array of routes
See
reload() public static ¶
reload( )
Reloads default Router settings. Resets all class variables and removes all connected routes.
resourceMap() public static ¶
resourceMap( array $resourceMap = null )
Resource map getter & setter.
Parameters
- array $resourceMap optional null
- Resource map
Returns
See
reverse() public static ¶
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.
Parameters
-
CakeRequest
|array $params - The params array or CakeRequest object that needs to be reversed.
- boolean $full optional false
Set to true to include the full url including the protocol when reversing the url.
Returns
The string that is the reversed result of the array
setRequestInfo() public static ¶
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.
Parameters
-
CakeRequest
|array $request - Parameters and path information or a CakeRequest object.
stripPlugin() public static ¶
stripPlugin( string $base , string $plugin = null )
Removes the plugin name from the base URL.
Parameters
- string $base
- Base URL
- string $plugin optional null
- Plugin name
Returns
base url with plugin name removed if present
url() public static ¶
url( mixed $url = null , mixed $full = false )
Finds URL for specified action.
Returns an URL pointing to a combination of controller and action. Param $url can be:
- Empty - the method will find address to actual controller/action.
- '/' - the method will find base URL of application.
- A combination of controller/action - the method will find url for it.
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 theFULL_BASE_URL
constant will be prepended to generated urls.
Parameters
- mixed $url optional null
Cake-relative URL, like "/products/edit/92" or "/presidents/elect/4" or an array specifying any of the following: 'controller', 'action', and/or 'plugin', in addition to named arguments (keyed array elements), and standard URL arguments (indexed array elements)
- mixed $full optional false
If (bool) true, the full base URL will be prepended to the result. If an array accepts the following keys - escape - used when making urls embedded in html escapes query string '&' - full - if true the full base URL will be prepended.
Returns
Full translated URL with base path.
Properties detail
$_initialState ¶
Initial state is populated the first time reload() is called which is at the bottom of this file. This is a cheat as get_class_vars() returns the value of static vars even if they have changed.
array()
$_namedConfig ¶
Stores all information necessary to decide what named arguments are parsed under what conditions.
array( 'default' => array('page', 'fields', 'order', 'limit', 'recursive', 'sort', 'direction', 'step'), 'greedyNamed' => true, 'separator' => ':', 'rules' => false, )
$_namedExpressions ¶
Named expressions
array( 'Action' => Router::ACTION, 'Year' => Router::YEAR, 'Month' => Router::MONTH, 'Day' => Router::DAY, 'ID' => Router::ID, 'UUID' => Router::UUID )
$_parseExtensions ¶
Directive for Router to parse out file extensions for mapping to Content-types.
false
$_prefixes ¶
List of action prefixes used in connected routes. Includes admin prefix
array()
$_requests ¶
Maintains the request object stack for the current request. This will contain more than one request object when requestAction is used.
array()
$_resourceMap ¶
Default HTTP request method => controller action map.
array( array('action' => 'index', 'method' => 'GET', 'id' => false), array('action' => 'view', 'method' => 'GET', 'id' => true), array('action' => 'add', 'method' => 'POST', 'id' => false), array('action' => 'edit', 'method' => 'PUT', 'id' => true), array('action' => 'delete', 'method' => 'DELETE', 'id' => true), array('action' => 'edit', 'method' => 'POST', 'id' => true) )
$_validExtensions ¶
List of valid extensions to parse from a URL. If null, any extension is allowed.
array()