CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 1.3 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 1.3
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Classes

  • AclBase
  • AclBehavior
  • AclComponent
  • AclNode
  • AclShell
  • Aco
  • AcoAction
  • AjaxHelper
  • ApcEngine
  • ApiShell
  • App
  • AppController
  • AppHelper
  • AppModel
  • Aro
  • AuthComponent
  • BakeShell
  • BakeTask
  • BehaviorCollection
  • Cache
  • CacheEngine
  • CacheHelper
  • CakeErrorController
  • CakeLog
  • CakeRoute
  • CakeSchema
  • CakeSession
  • CakeSocket
  • ClassRegistry
  • Component
  • Configure
  • ConnectionManager
  • ConsoleShell
  • ContainableBehavior
  • Controller
  • ControllerTask
  • CookieComponent
  • DataSource
  • DbAcl
  • DbConfigTask
  • DboMssql
  • DboMysql
  • DboMysqlBase
  • DboMysqli
  • DboOracle
  • DboPostgres
  • DboSource
  • DboSqlite
  • Debugger
  • EmailComponent
  • ErrorHandler
  • ExtractTask
  • File
  • FileEngine
  • FileLog
  • FixtureTask
  • Folder
  • FormHelper
  • Helper
  • HtmlHelper
  • HttpSocket
  • I18n
  • I18nModel
  • I18nShell
  • Inflector
  • IniAcl
  • JavascriptHelper
  • JqueryEngineHelper
  • JsBaseEngineHelper
  • JsHelper
  • L10n
  • MagicDb
  • MagicFileResource
  • MediaView
  • MemcacheEngine
  • Model
  • ModelBehavior
  • ModelTask
  • MootoolsEngineHelper
  • Multibyte
  • NumberHelper
  • Object
  • Overloadable
  • Overloadable2
  • PagesController
  • PaginatorHelper
  • Permission
  • PluginShortRoute
  • PluginTask
  • ProjectTask
  • PrototypeEngineHelper
  • RequestHandlerComponent
  • Router
  • RssHelper
  • Sanitize
  • Scaffold
  • ScaffoldView
  • SchemaShell
  • Security
  • SecurityComponent
  • SessionComponent
  • SessionHelper
  • Set
  • Shell
  • String
  • TemplateTask
  • TestSuiteShell
  • TestTask
  • TextHelper
  • ThemeView
  • TimeHelper
  • TranslateBehavior
  • TreeBehavior
  • Validation
  • View
  • ViewTask
  • XcacheEngine
  • Xml
  • XmlElement
  • XmlHelper
  • XmlManager
  • XmlNode
  • XmlTextNode

Functions

  • mb_encode_mimeheader
  • mb_stripos
  • mb_stristr
  • mb_strlen
  • mb_strpos
  • mb_strrchr
  • mb_strrichr
  • mb_strripos
  • mb_strrpos
  • mb_strstr
  • mb_strtolower
  • mb_strtoupper
  • mb_substr
  • mb_substr_count

Class Router

Parses the request URL into controller, action, and parameters.

Package: cake\cake\libs
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 public
    boolean
    Keeps track of whether the connection of default routes is enabled or disabled.
  • $__currentRoute public
    array
    The route matching the URL of the current request
  • $__defaultsMapped public
    boolean
    Keeps Router state to determine if default routes have already been connected
  • $__named public
    array
    'Constant' regular expression definitions for named route elements
  • $__params public
    array
    Maintains the parameter stack for the current request
  • $__parseExtensions public
    boolean
    Directive for Router to parse out file extensions for mapping to Content-types.
  • $__paths public
    array
    Maintains the path stack for the current request
  • $__prefixes public
    array

    List of action prefixes used in connected routes. Includes admin prefix

  • $__resourceMap public
    array
    Default HTTP request method => controller action map.
  • $__resourceMapped public
    array
    List of resource-mapped controllers
  • $__validExtensions public
    array
    List of valid extensions to parse from a URL. If null, any extension is allowed.
  • $named public
    string
    Stores all information necessary to decide what named arguments are parsed under what conditions.
  • $routes public
    array
    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

Router() public ¶

Router( )

Constructor for Router. Builds __prefixes

__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
array
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
string
A generated url for the array
See
Router::url()

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
Array of routes
See
Router::$routes

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
array

currentRoute() public ¶

currentRoute( )

Returns the route matching the current request (useful for requestAction traces)

Returns
CakeRoute
Matching route object.

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
Array containing passed and named parameters

getInstance() public ¶

getInstance( )

Gets a reference to the Router object instance

Returns
Router
Instance of the Router.

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
array

getNamedExpressions() public ¶

getNamedExpressions( )

Gets the named route elements for use in app/config/routes.php

Returns
array
Named route elements
See
Router::$__named

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
string
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
array
Parameter information

getPaths() public ¶

getPaths( boolean $current = false )

Gets path information

Parameters
boolean $current optional false
Current parameter, useful when using requestAction
Returns
array

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
boolean

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
string
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
array
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
array
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
boolean
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
array

reload() public ¶

reload( )

Reloads default Router settings. Resets all class variables and removes all connected routes.

requestRoute() public ¶

requestRoute( )

Returns the route matching the current request URL.

Returns
CakeRoute
Matching route object.

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
string
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
base
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 the FULL_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
string
Full translated URL with base path.

Properties detail

$__connectDefaults ¶

public boolean

Keeps track of whether the connection of default routes is enabled or disabled.

true

$__currentRoute ¶

public array

The route matching the URL of the current request

array()

$__defaultsMapped ¶

public boolean

Keeps Router state to determine if default routes have already been connected

false

$__named ¶

public array

'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}'
)

$__params ¶

public array

Maintains the parameter stack for the current request

array()

$__parseExtensions ¶

public boolean

Directive for Router to parse out file extensions for mapping to Content-types.

false

$__paths ¶

public array

Maintains the path stack for the current request

array()

$__prefixes ¶

public array

List of action prefixes used in connected routes. Includes admin prefix

array()

$__resourceMap ¶

public array

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)
)

$__resourceMapped ¶

public array

List of resource-mapped controllers

array()

$__validExtensions ¶

public array

List of valid extensions to parse from a URL. If null, any extension is allowed.

null

$named ¶

public string

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'),
    'greedy' => true,
    'separator' => ':',
    'rules' => false,
)

$routes ¶

public array

Array of routes connected with Router::connect()

array()
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs