Class Router
Parses the request URL into controller, action, and parameters.
Copyright: Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Location: router.php
Properties summary
-
$__connectDefaults
publicboolean
Keeps track of whether the connection of default routes is enabled or disabled. -
$__currentRoute
publicarray
The route matching the URL of the current request -
$__defaultsMapped
publicboolean
Keeps Router state to determine if default routes have already been connected -
$__named
publicarray
'Constant' regular expression definitions for named route elements -
$__params
publicarray
Maintains the parameter stack for the current request -
$__parseExtensions
publicboolean
Directive for Router to parse out file extensions for mapping to Content-types. -
$__paths
publicarray
Maintains the path stack for the current request -
$__prefixes
publicarray
List of action prefixes used in connected routes. Includes admin prefix
-
$__resourceMap
publicarray
Default HTTP request method => controller action map. -
$__resourceMapped
publicarray
List of resource-mapped controllers -
$__validExtensions
publicarray
List of valid extensions to parse from a URL. If null, any extension is allowed. -
$named
publicstring
Stores all information necessary to decide what named arguments are parsed under what conditions. -
$routes
publicarray
Array of routes connected with Router::connect()
Method Summary
-
Router() public
Constructor for Router. Builds __prefixes
-
__connectDefaultRoutes() public
Connects the default, built-in routes, including prefix and plugin routes. The following routes are created in the order below:
-
__parseExtension() public
Parses a file extension out of a URL, if Router::parseExtensions() is enabled. -
__setPrefixes() public
Sets the Routing prefixes. Includes compatibility for existing Routing.admin configurations.
-
_handleNoRoute() public
A special fallback method that handles url arrays that cannot match any defined routes.
-
connect() public
Connects a new Route in the router. -
connectNamed() public
Specifies what named parameters CakePHP should be parsing. The most common setups are: -
currentRoute() public
Returns the route matching the current request (useful for requestAction traces) -
defaults() public
Tell router to connect or not connect the default routes. -
getArgs() public
Takes a passed params and converts it to args -
getInstance() public
Gets a reference to the Router object instance -
getNamedElements() public
Takes an array of URL parameters and separates the ones that can be used as named arguments -
getNamedExpressions() public
Gets the named route elements for use in app/config/routes.php -
getParam() public
Gets URL parameter by name -
getParams() public
Gets parameter information -
getPaths() public
Gets path information -
mapResources() public
Creates REST resource routes for the given controller(s) -
matchNamed() public
Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented rule types are controller, action and match that can be combined with each other.
-
normalize() public
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
Parses given URL and returns an array of controller, action and parameters taken from that URL.
-
parseExtensions() public
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['url']['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.
-
prefixes() public
Returns the list of prefixes used in connected routes -
promote() public
Promote a route (by default, the last one added) to the beginning of the list -
queryString() public
Generates a well-formed querystring from $q -
reload() public
Reloads default Router settings. Resets all class variables and removes all connected routes.
-
requestRoute() public
Returns the route matching the current request URL. -
reverse() public
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
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
Removes the plugin name from the base URL. -
url() public
Finds URL for specified action.
Method Detail
__connectDefaultRoutes() public ¶
__connectDefaultRoutes( )
Connects the default, built-in routes, including prefix and plugin routes. The following routes are created in the order below:
For each of the Routing.prefixes the following routes are created. Routes containing :plugin
are only
created when your application has one or more plugins.
/:prefix/:plugin
a plugin shortcut route./:prefix/:plugin/:action/*
a plugin shortcut route./:prefix/:plugin/:controller
/:prefix/:plugin/:controller/:action/*
/:prefix/:controller
/:prefix/:controller/:action/*
If plugins are found in your application the following routes are created:
/:plugin
a plugin shortcut route./:plugin/:action/*
a plugin shortcut route./:plugin/:controller
/:plugin/:controller/:action/*
And lastly the following catch-all routes are connected.
- `/:controller'
- `/:controller/:action/*'
You can disable the connection of default routes with Router::defaults().
__parseExtension() public ¶
__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.
__setPrefixes() public ¶
__setPrefixes( )
Sets the Routing prefixes. Includes compatibility for existing Routing.admin configurations.
_handleNoRoute() public ¶
_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
connect() public ¶
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 three 'special' keys. pass
, 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'
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
See
connectNamed() public ¶
connectNamed( array $named , array $options = array() )
Specifies what named parameters CakePHP should be parsing. The most common setups are:
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 mater 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) ); }}}
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 ¶
currentRoute( )
Returns the route matching the current request (useful for requestAction traces)
Returns
defaults() public ¶
defaults( boolean $connect = true )
Tell router to connect or not connect the default routes.
If default routes are disabled all automatic route generation will be disabled and you will need to manually configure all the routes you want.
Parameters
- boolean $connect optional true
- Set to true or false depending on whether you want or don't want default routes.
getArgs() public ¶
getArgs( array $args , $options = array() )
Takes a passed params and converts it to args
Parameters
- array $args
- $params
- $options optional array()
Returns
Array containing passed and named parameters
getNamedElements() public ¶
getNamedElements( array $params , string $controller = null , string $action = null )
Takes an array of URL parameters and separates the ones that can be used as named arguments
Parameters
- array $params
- Associative array of URL parameters.
- string $controller optional null
- Name of controller being routed. Used in scoping.
- string $action optional null
- Name of action being routed. Used in scoping.
Returns
getNamedExpressions() public ¶
getNamedExpressions( )
Gets the named route elements for use in app/config/routes.php
Returns
Named route elements
See
getParam() public ¶
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 ¶
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 ¶
getPaths( boolean $current = false )
Gets path information
Parameters
- boolean $current optional false
- Current parameter, useful when using requestAction
Returns
mapResources() public ¶
mapResources( mixed $controller , array $options = array() )
Creates REST resource routes for the given controller(s)
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
matchNamed() public ¶
matchNamed( string $param , string $val , array $rule , string $context = array() )
Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented rule types are controller, action and match that can be combined with each other.
Parameters
- string $param
- The name of the named parameter
- string $val
- The value of the named parameter
- array $rule
- The rule(s) to apply, can also be a match string
- string $context optional array()
- An array with additional context information (controller / action)
Returns
normalize() public ¶
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 ¶
parse( string $url )
Parses given URL and returns an array of controller, action and parameters taken from that URL.
Parameters
- string $url
- URL to be parsed
Returns
Parsed elements from URL
parseExtensions() public ¶
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['url']['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.
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=...).
prefixes() public ¶
prefixes( )
Returns the list of prefixes used in connected routes
Returns
A list of prefixes used in connected routes
promote() public ¶
promote( $which = null )
Promote a route (by default, the last one added) to the beginning of the list
Parameters
- $which optional null
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 ¶
queryString( mixed $q , array $extra = array() , boolean $escape = false )
Generates a well-formed querystring from $q
Parameters
- mixed $q
- Query string
- array $extra optional array()
- Extra querystring parameters.
- boolean $escape optional false
- Whether or not to use escaped &
Returns
reload() public ¶
reload( )
Reloads default Router settings. Resets all class variables and removes all connected routes.
reverse() public ¶
reverse( array $params )
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
- array $params
- $param The params array that needs to be reversed.
Returns
The string that is the reversed result of the array
setRequestInfo() public ¶
setRequestInfo( array $params )
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.
Parameters
- array $params
- Parameters and path information
stripPlugin() public ¶
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
url with plugin name removed if present
url() public ¶
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
$__connectDefaults ¶
Keeps track of whether the connection of default routes is enabled or disabled.
true
$__defaultsMapped ¶
Keeps Router state to determine if default routes have already been connected
false
$__named ¶
'Constant' regular expression definitions for named route elements
array( 'Action' => 'index|show|add|create|edit|update|remove|del|delete|view|item', 'Year' => '[12][0-9]{3}', 'Month' => '0[1-9]|1[012]', 'Day' => '0[1-9]|[12][0-9]|3[01]', 'ID' => '[0-9]+', '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}' )
$__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()
$__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.
null