Fr3nch13/CakePHP Utilities

Router
in package

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. For more information on routes and how to connect them see Router::connect().

Table of Contents

Constants

ACTION  = 'index|show|add|create|edit|update|remove|del|delete|view|item'
Regular expression for action names
DAY  = '0[1-9]|[12][0-9]|3[01]'
Regular expression for days
ID  = '[0-9]+'
Regular expression for auto increment IDs
MONTH  = '0[1-9]|1[012]'
Regular expression for months
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
YEAR  = '[12][0-9]{3}'
Regular expression for years

Properties

$_collection  : RouteCollection
The route collection routes would be added to.
$_defaultExtensions  : array<string|int, string>
Default extensions defined with Router::extensions()
$_defaultRouteClass  : string
Default route class.
$_fullBaseUrl  : string|null
Contains the base string that will be applied to all generated URLs For example `https://example.com`
$_initialState  : array<string|int, mixed>
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.
$_namedExpressions  : array<string, string>
Named expressions
$_request  : ServerRequest
Maintains the request object reference.
$_requestContext  : array<string, mixed>
A hash of request context data.
$_routePaths  : array<string, mixed>
Cache of parsed route paths
$_urlFilters  : array<string|int, callable>
The stack of URL filters to apply against routing URLs before passing the parameters to the route collection.

Methods

addUrlFilter()  : void
Add a URL filter to Router.
connect()  : void
Connects a new Route in the router.
createRouteBuilder()  : RouteBuilder
Create a RouteBuilder for the provided path.
defaultRouteClass()  : string|null
Get or set default route class.
extensions()  : array<string|int, string>
Get or set valid extensions for all routes connected later.
fullBaseUrl()  : string
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.
getNamedExpressions()  : array<string, string>
Gets the named route patterns for use in config/routes.php
getRequest()  : ServerRequest|null
Get the current request object.
getRouteCollection()  : RouteCollection
Get the RouteCollection inside the Router
normalize()  : string
Normalizes a URL for purposes of comparison.
parseRequest()  : array<string|int, mixed>
Get the routing parameters for the request if possible.
parseRoutePath()  : array<string, string>
Parse a string route path
pathUrl()  : string
Generate URL for route path.
plugin()  : void
Add plugin routes.
prefix()  : void
Create prefixed routes.
reload()  : void
Reloads default Router settings. Resets all class variables and removes all connected routes.
reverse()  : string
Reverses a parsed parameter array into a string.
reverseToArray()  : array<string|int, mixed>
Reverses a parsed parameter array into an array.
routeExists()  : bool
Finds URL for specified action.
routes()  : array<string|int, Route>
Get the route scopes and their connected routes.
scope()  : void
Create a routing scope.
setRequest()  : void
Set current request instance.
setRouteCollection()  : void
Set the RouteCollection inside the Router
url()  : string
Finds URL for specified action.
_applyUrlFilters()  : array<string|int, mixed>
Applies all the connected URL filters to the URL.
unwrapShortString()  : array<string|int, mixed>
Inject route defaults from `_path` key

Constants

ACTION

Regular expression for action names

public string ACTION = 'index|show|add|create|edit|update|remove|del|delete|view|item'

DAY

Regular expression for days

public string DAY = '0[1-9]|[12][0-9]|3[01]'

ID

Regular expression for auto increment IDs

public string ID = '[0-9]+'

MONTH

Regular expression for months

public string MONTH = '0[1-9]|1[012]'

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

YEAR

Regular expression for years

public string YEAR = '[12][0-9]{3}'

Properties

$_collection

The route collection routes would be added to.

protected static RouteCollection $_collection

$_defaultExtensions

Default extensions defined with Router::extensions()

protected static array<string|int, string> $_defaultExtensions = []

$_defaultRouteClass

Default route class.

protected static string $_defaultRouteClass = \Cake\Routing\Route\Route::class

$_fullBaseUrl

Contains the base string that will be applied to all generated URLs For example `https://example.com`

protected static string|null $_fullBaseUrl

$_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.

protected static array<string|int, mixed> $_initialState = []

$_namedExpressions

Named expressions

protected static array<string, string> $_namedExpressions = ['Action' => \Cake\Routing\Router::ACTION, 'Year' => \Cake\Routing\Router::YEAR, 'Month' => \Cake\Routing\Router::MONTH, 'Day' => \Cake\Routing\Router::DAY, 'ID' => \Cake\Routing\Router::ID, 'UUID' => \Cake\Routing\Router::UUID]

$_requestContext

A hash of request context data.

protected static array<string, mixed> $_requestContext = []

$_routePaths

Cache of parsed route paths

protected static array<string, mixed> $_routePaths = []

$_urlFilters

The stack of URL filters to apply against routing URLs before passing the parameters to the route collection.

protected static array<string|int, callable> $_urlFilters = []

Methods

addUrlFilter()

Add a URL filter to Router.

public static addUrlFilter(callable $function) : void

URL filter functions are applied to every array $url provided to Router::url() before the URLs are sent to the route collection.

Callback functions should expect the following parameters:

  • $params The URL params being processed.
  • $request The current request.

The URL filter function should always return the params even if unmodified.

Usage

URL filters allow you to easily implement features like persistent parameters.

Router::addUrlFilter(function ($params, $request) {
 if ($request->getParam('lang') && !isset($params['lang'])) {
   $params['lang'] = $request->getParam('lang');
 }
 return $params;
});
Parameters
$function : callable

The function to add

connect()

Connects a new Route in the router.

public static connect(Route|string $route[, array<string|int, mixed>|string $defaults = [] ][, array<string, mixed> $options = [] ]) : void

Use the non-static method RouteBuilder::connect() instead.

Compatibility proxy to \Cake\Routing\RouteBuilder::connect() in the / scope.

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
throws
CakeException
see
RouteBuilder::connect()
see
Router::scope()

createRouteBuilder()

Create a RouteBuilder for the provided path.

public static createRouteBuilder(string $path[, array<string, mixed> $options = [] ]) : RouteBuilder
Parameters
$path : string

The path to set the builder to.

$options : array<string, mixed> = []

The options for the builder

Return values
RouteBuilder

defaultRouteClass()

Get or set default route class.

public static defaultRouteClass([string|null $routeClass = null ]) : string|null
Parameters
$routeClass : string|null = null

Class name.

Return values
string|null

extensions()

Get or set valid extensions for all routes connected later.

public static extensions([array<string|int, string>|string|null $extensions = null ][, bool $merge = true ]) : array<string|int, string>

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->request->getParam('_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 Cake\Http\Response.

A string or an array of valid extensions can be passed to this method. If called without any parameters it will return current list of set extensions.

Parameters
$extensions : array<string|int, string>|string|null = null

List of extensions to be added.

$merge : bool = true

Whether to merge with or override existing extensions. Defaults to true.

Return values
array<string|int, string>

Array of extensions Router is configured to parse.

fullBaseUrl()

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.

public static fullBaseUrl([string|null $base = null ]) : string

Note:

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.

Parameters
$base : string|null = null

the prefix for URLs generated containing the domain. For example: http://example.com

Return values
string

getNamedExpressions()

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

public static getNamedExpressions() : array<string, string>
Tags
see
Router::$_namedExpressions
Return values
array<string, string>

Named route elements

getRouteCollection()

Get the RouteCollection inside the Router

public static getRouteCollection() : RouteCollection
Return values
RouteCollection

normalize()

Normalizes a URL for purposes of comparison.

public static normalize([array<string|int, mixed>|string $url = '/' ]) : string

Will strip the base path off and replace any double /'s. It will not unify the casing and underscoring of the input value.

Parameters
$url : array<string|int, mixed>|string = '/'

URL to normalize Either an array or a string URL.

Return values
string

Normalized URL

parseRequest()

Get the routing parameters for the request if possible.

public static parseRequest(ServerRequest $request) : array<string|int, mixed>
Parameters
$request : ServerRequest

The request to parse request data from.

Tags
throws
MissingRouteException

When a route cannot be handled

Return values
array<string|int, mixed>

Parsed elements from URL.

parseRoutePath()

Parse a string route path

public static parseRoutePath(string $url) : array<string, string>

String examples:

  • Bookmarks::view
  • Admin/Bookmarks::view
  • Cms.Articles::edit
  • Vendor/Cms.Management/Admin/Articles::view
Parameters
$url : string

Route path in [Plugin.][Prefix/]Controller::action format

Return values
array<string, string>

pathUrl()

Generate URL for route path.

public static pathUrl(string $path[, array<string|int, mixed> $params = [] ][, bool $full = false ]) : string

Route path examples:

  • Bookmarks::view
  • Admin/Bookmarks::view
  • Cms.Articles::edit
  • Vendor/Cms.Management/Admin/Articles::view
Parameters
$path : string

Route path specifying controller and action, optionally with plugin and prefix.

$params : array<string|int, mixed> = []

An array specifying any additional parameters. Can be also any special parameters supported by Router::url().

$full : bool = false

If true, the full base URL will be prepended to the result. Default is false.

Return values
string

Full translated URL with base path.

plugin()

Add plugin routes.

public static plugin(string $name[, callable|array<string|int, mixed> $options = [] ][, callable|null $callback = null ]) : void

Use the non-static method RouteBuilder::plugin() instead.

This method creates a scoped route collection that includes relevant plugin information.

The plugin name will be inflected to the dasherized 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.

Parameters
$name : string

The plugin name to build routes for

$options : callable|array<string|int, mixed> = []

Either the options to use, or a callback

$callback : callable|null = null

The callback to invoke that builds the plugin routes. Only required when $options is defined

prefix()

Create prefixed routes.

public static prefix(string $name[, callable|array<string|int, mixed> $params = [] ][, callable|null $callback = null ]) : void

Use the non-static method RouteBuilder::prefix() instead.

This method creates a scoped route collection that includes relevant prefix information.

The path 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.

The prefix name will be inflected to the dasherized version to create the routing path. If you want a custom path name, use the path option.

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.

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.

reload()

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

public static reload() : void

reverse()

Reverses a parsed parameter array into a string.

public static reverse(ServerRequest|array<string|int, mixed> $params[, bool $full = false ]) : string

Works similarly to Router::url(), but since parsed URL's contain additional keys like 'pass', '_matchedRoute' etc. those keys need to be specially handled in order to reverse a params array into a string URL.

Parameters
$params : ServerRequest|array<string|int, mixed>

The params array or Cake\Http\ServerRequest object that needs to be reversed.

$full : bool = false

Set to true to include the full URL including the protocol when reversing the URL.

Return values
string

The string that is the reversed result of the array

reverseToArray()

Reverses a parsed parameter array into an array.

public static reverseToArray(ServerRequest|array<string|int, mixed> $params) : array<string|int, mixed>

Works similarly to Router::url(), but since parsed URL's contain additional keys like 'pass', '_matchedRoute' etc. those keys need to be specially handled in order to reverse a params array into a string URL.

Parameters
$params : ServerRequest|array<string|int, mixed>

The params array or Cake\Http\ServerRequest object that needs to be reversed.

Return values
array<string|int, mixed>

The URL array ready to be used for redirect or HTML link.

routeExists()

Finds URL for specified action.

public static routeExists([array<string|int, mixed>|string|null $url = null ][, bool $full = false ]) : bool

Returns a bool if the url exists

Usage

Parameters
$url : array<string|int, mixed>|string|null = null

An array specifying any of the following: 'controller', 'action', 'plugin' additionally, you can provide routed elements or query string parameters. If string it can be name any valid url string.

$full : bool = false

If true, the full base URL will be prepended to the result. Default is false.

Tags
see
Router::url()
Return values
bool

routes()

Get the route scopes and their connected routes.

public static routes() : array<string|int, Route>
Return values
array<string|int, Route>

scope()

Create a routing scope.

public static scope(string $path[, callable|array<string|int, mixed> $params = [] ][, callable|null $callback = null ]) : void

Use the non-static method RouteBuilder::scope() instead.

Routing scopes allow you to keep your routes DRY and avoid repeating common path prefixes, and or parameter sets.

Scoped collections will be indexed by path for faster route parsing. If you re-open or re-use a scope the connected routes will be merged with the existing ones.

Options

The $params array allows you to define options for the routing scope. The options listed below are not available to be used as routing defaults

  • routeClass The route class to use in this scope. Defaults to Router::defaultRouteClass()
  • extensions The extensions to enable in this scope. Defaults to the globally enabled extensions set with Router::extensions()

Example

Router::scope('/blog', ['plugin' => 'Blog'], function ($routes) {
   $routes->connect('/', ['controller' => 'Articles']);
});

The above would result in a /blog/ route being created, with both the plugin & controller default parameters set.

You can use Router::plugin() and Router::prefix() as shortcuts to creating specific kinds of scopes.

Parameters
$path : string

The path prefix for the scope. This path will be prepended to all routes connected in the scoped collection.

$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 with the scoped collection.

Tags
throws
InvalidArgumentException

When an invalid callable is provided.

setRouteCollection()

Set the RouteCollection inside the Router

public static setRouteCollection(RouteCollection $routeCollection) : void
Parameters
$routeCollection : RouteCollection

route collection

url()

Finds URL for specified action.

public static url([UriInterface|array<string|int, mixed>|string|null $url = null ][, bool $full = false ]) : string

Returns a URL pointing to a combination of controller and action.

Usage

  • Router::url('/posts/edit/1'); Returns the string with the base dir prepended. This usage does not use reverser routing.
  • Router::url(['controller' => 'Posts', 'action' => 'edit']); Returns a URL generated through reverse routing.
  • Router::url(['_name' => 'custom-name', ...]); Returns a URL generated through reverse routing. This form allows you to leverage named routes.

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.
  • _scheme - Set to create links on different schemes like webcal or ftp. Defaults to the current scheme.
  • _host - Set the host to use for the link. Defaults to the current host.
  • _port - Set the port if you need to create links on non-standard ports.
  • _full - If true output of Router::fullBaseUrl() will be prepended to generated URLs.
  • # - Allows you to set URL hash fragments.
  • _ssl - Set to true to convert the generated URL to https, or false to force http.
  • _name - Name of route. If you have setup named routes you can use this key to specify it.
Parameters
$url : UriInterface|array<string|int, mixed>|string|null = null

An array specifying any of the following: 'controller', 'action', 'plugin' additionally, you can provide routed elements or query string parameters. If string it can be name any valid url string or it can be an UriInterface instance.

$full : bool = false

If true, the full base URL will be prepended to the result. Default is false.

Tags
throws
CakeException

When the route name is not found

Return values
string

Full translated URL with base path.

_applyUrlFilters()

Applies all the connected URL filters to the URL.

protected static _applyUrlFilters(array<string|int, mixed> $url) : array<string|int, mixed>
Parameters
$url : array<string|int, mixed>

The URL array being modified.

Tags
see
Router::url()
see
Router::addUrlFilter()
Return values
array<string|int, mixed>

The modified URL.

unwrapShortString()

Inject route defaults from `_path` key

protected static unwrapShortString(array<string|int, mixed> $url) : array<string|int, mixed>
Parameters
$url : array<string|int, mixed>

Route array with _path key

Return values
array<string|int, mixed>

        
On this page

Search results