Class yii\web\UrlManager

Inheritanceyii\web\UrlManager » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/web/UrlManager.php

UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.

UrlManager is configured as an application component in yii\base\Application by default. You can access that instance via Yii::$app->urlManager.

You can modify its configuration by adding an array to your application config under components as it is shown in the following example:

'urlManager' => [
    'enablePrettyUrl' => true,
    'rules' => [
        // your rules go here
    ],
    // ...
]

Rules are classes implementing the yii\web\UrlRuleInterface, by default that is yii\web\UrlRule. For nesting rules, there is also a yii\web\GroupUrlRule class.

For more details and usage information on UrlManager, see the guide article on routing.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$baseUrl string The base URL that is used by createUrl() to prepend to created URLs. yii\web\UrlManager
$behaviors yii\base\Behavior[] List of behaviors attached to this component. This property is read-only. yii\base\Component
$cache yii\caching\CacheInterface|array|string|boolean The cache object or the application component ID of the cache object. yii\web\UrlManager
$enablePrettyUrl boolean Whether to enable pretty URLs. yii\web\UrlManager
$enableStrictParsing boolean Whether to enable strict parsing. yii\web\UrlManager
$hostInfo string The host info (e.g. http://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs. yii\web\UrlManager
$normalizer yii\web\UrlNormalizer|array|string|false The configuration for yii\web\UrlNormalizer used by this UrlManager. yii\web\UrlManager
$routeParam string The GET parameter name for route. yii\web\UrlManager
$ruleConfig array The default configuration of URL rules. yii\web\UrlManager
$rules array The rules for creating and parsing URLs when $enablePrettyUrl is true. yii\web\UrlManager
$scriptUrl string The entry script URL that is used by createUrl() to prepend to created URLs. yii\web\UrlManager
$showScriptName boolean Whether to show entry script name in the constructed URL. yii\web\UrlManager
$suffix string The URL suffix used when $enablePrettyUrl is true. yii\web\UrlManager

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$cacheKey string The cache key for cached rules yii\web\UrlManager

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
addRules() Adds additional URL rules. yii\web\UrlManager
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
createAbsoluteUrl() Creates an absolute URL using the given route and query parameters. yii\web\UrlManager
createUrl() Creates a URL using the given route and query parameters. yii\web\UrlManager
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getBaseUrl() Returns the base URL that is used by createUrl() to prepend to created URLs. yii\web\UrlManager
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getHostInfo() Returns the host info that is used by createAbsoluteUrl() to prepend to created URLs. yii\web\UrlManager
getScriptUrl() Returns the entry script URL that is used by createUrl() to prepend to created URLs. yii\web\UrlManager
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes UrlManager. yii\web\UrlManager
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
parseRequest() Parses the user request. yii\web\UrlManager
setBaseUrl() Sets the base URL that is used by createUrl() to prepend to created URLs. yii\web\UrlManager
setHostInfo() Sets the host info that is used by createAbsoluteUrl() to prepend to created URLs. yii\web\UrlManager
setScriptUrl() Sets the entry script URL that is used by createUrl() to prepend to created URLs. yii\web\UrlManager
trigger() Triggers an event. yii\base\Component

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
buildRules() Builds URL rule objects from the given rule declarations. yii\web\UrlManager
canBeCached() Returns the value indicating whether result of createUrl() of rule should be cached in internal cache. yii\web\UrlManager
getBuiltRulesFromCache() Provides the built URL rules that are associated with the $ruleDeclarations from cache. yii\web\UrlManager
getUrlFromCache() Get URL from internal cache if exists. yii\web\UrlManager
setBuiltRulesCache() Stores $builtRules to cache, using $rulesDeclaration as a part of cache key. yii\web\UrlManager
setRuleToCache() Store rule (e.g. yii\web\UrlRule) to internal cache. yii\web\UrlManager

Property Details

$baseUrl public property

The base URL that is used by createUrl() to prepend to created URLs.

public string $baseUrl null
$cache public property

The cache object or the application component ID of the cache object. This can also be an array that is used to create a yii\caching\CacheInterface instance in case you do not want to use an application component. Compiled URL rules will be cached through this cache object, if it is available.

After the UrlManager object is created, if you want to change this property, you should only assign it with a cache object. Set this property to false or null if you do not want to cache the URL rules.

Cache entries are stored for the time set by $defaultDuration in the cache configuration, which is unlimited by default. You may want to tune this value if your $rules change frequently.

$cacheKey protected property (available since version 2.0.8)

The cache key for cached rules

protected string $cacheKey __CLASS__
$enablePrettyUrl public property

Whether to enable pretty URLs. Instead of putting all parameters in the query string part of a URL, pretty URLs allow using path info to represent some of the parameters and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of "/index.php?r=news%2Fview&id=100".

public boolean $enablePrettyUrl false
$enableStrictParsing public property

Whether to enable strict parsing. If strict parsing is enabled, the incoming requested URL must match at least one of the $rules in order to be treated as a valid request. Otherwise, the path info part of the request will be treated as the requested route. This property is used only when $enablePrettyUrl is true.

$hostInfo public property

The host info (e.g. http://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs.

public string $hostInfo null
$normalizer public property (available since version 2.0.10)

The configuration for yii\web\UrlNormalizer used by this UrlManager. The default value is false, which means normalization will be skipped. If you wish to enable URL normalization, you should configure this property manually. For example:

[
    'class' => 'yii\web\UrlNormalizer',
    'collapseSlashes' => true,
    'normalizeTrailingSlash' => true,
]
$routeParam public property

The GET parameter name for route. This property is used only if $enablePrettyUrl is false.

public string $routeParam 'r'
$ruleConfig public property

The default configuration of URL rules. Individual rule configurations specified via $rules will take precedence when the same property of the rule is configured.

public array $ruleConfig = ['class' => 'yii\web\UrlRule']
$rules public property

The rules for creating and parsing URLs when $enablePrettyUrl is true. This property is used only if $enablePrettyUrl is true. Each element in the array is the configuration array for creating a single URL rule. The configuration will be merged with $ruleConfig first before it is used for creating the rule object.

A special shortcut format can be used if a rule only specifies pattern and route: 'pattern' => 'route'. That is, instead of using a configuration array, one can use the key to represent the pattern and the value the corresponding route. For example, 'post/<id:\d+>' => 'post/view'.

For RESTful routing the mentioned shortcut format also allows you to specify the HTTP verb that the rule should apply for. You can do that by prepending it to the pattern, separated by space. For example, 'PUT post/<id:\d+>' => 'post/update'. You may specify multiple verbs by separating them with comma like this: 'POST,PUT post/index' => 'post/create'. The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE. Note that mode will be set to PARSING_ONLY when specifying verb in this way so you normally would not specify a verb for normal GET request.

Here is an example configuration for RESTful CRUD controller:

[
    'dashboard' => 'site/index',

    'POST <controller:[\w-]+>' => '<controller>/create',
    '<controller:[\w-]+>s' => '<controller>/index',

    'PUT <controller:[\w-]+>/<id:\d+>'    => '<controller>/update',
    'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
    '<controller:[\w-]+>/<id:\d+>'        => '<controller>/view',
];

Note that if you modify this property after the UrlManager object is created, make sure you populate the array with rule objects instead of rule configurations.

public array $rules = []
$scriptUrl public property

The entry script URL that is used by createUrl() to prepend to created URLs.

public string $scriptUrl null
$showScriptName public property

Whether to show entry script name in the constructed URL. Defaults to true. This property is used only if $enablePrettyUrl is true.

public boolean $showScriptName true
$suffix public property

The URL suffix used when $enablePrettyUrl is true. For example, ".html" can be used so that the URL looks like pointing to a static HTML page. This property is used only if $enablePrettyUrl is true.

public string $suffix null

Method Details

addRules() public method

Adds additional URL rules.

This method will call buildRules() to parse the given rule declarations and then append or insert them to the existing $rules.

Note that if $enablePrettyUrl is false, this method will do nothing.

public void addRules ( $rules, $append true )
$rules array

The new rules to be added. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule format.

$append boolean

Whether to add the new rules by appending them to the end of the existing rules.

buildRules() protected method

Builds URL rule objects from the given rule declarations.

protected yii\web\UrlRuleInterface[] buildRules ( $ruleDeclarations )
$ruleDeclarations array

The rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats.

return yii\web\UrlRuleInterface[]

The rule objects built from the given rule declarations

throws yii\base\InvalidConfigException

if a rule declaration is invalid

canBeCached() protected method (available since version 2.0.12)

Returns the value indicating whether result of createUrl() of rule should be cached in internal cache.

See also:

protected boolean canBeCached ( yii\web\UrlRuleInterface $rule )
$rule yii\web\UrlRuleInterface
return boolean

true if result should be cached, false if not.

createAbsoluteUrl() public method

Creates an absolute URL using the given route and query parameters.

This method prepends the URL created by createUrl() with the $hostInfo.

Note that unlike yii\helpers\Url::toRoute(), this method always treats the given route as an absolute route.

See also createUrl().

public string createAbsoluteUrl ( $params, $scheme null )
$params string|array

Use a string to represent a route (e.g. site/index), or an array to represent a route with query parameters (e.g. ['site/index', 'param1' => 'value1']).

$scheme string|null

The scheme to use for the URL (either http, https or empty string for protocol-relative URL). If not specified the scheme of the current request will be used.

return string

The created URL

createUrl() public method

Creates a URL using the given route and query parameters.

You may specify the route as a string, e.g., site/index. You may also use an array if you want to specify additional query parameters for the URL being created. The array format must be:

// generates: /index.php?r=site%2Findex&param1=value1&param2=value2
['site/index', 'param1' => 'value1', 'param2' => 'value2']

If you want to create a URL with an anchor, you can use the array format with a # parameter. For example,

// generates: /index.php?r=site%2Findex&param1=value1#name
['site/index', 'param1' => 'value1', '#' => 'name']

The URL created is a relative one. Use createAbsoluteUrl() to create an absolute URL.

Note that unlike yii\helpers\Url::toRoute(), this method always treats the given route as an absolute route.

public string createUrl ( $params )
$params string|array

Use a string to represent a route (e.g. site/index), or an array to represent a route with query parameters (e.g. ['site/index', 'param1' => 'value1']).

return string

The created URL

getBaseUrl() public method

Returns the base URL that is used by createUrl() to prepend to created URLs.

It defaults to yii\web\Request::$baseUrl. This is mainly used when $enablePrettyUrl is true and $showScriptName is false.

public string getBaseUrl ( )
return string

The base URL that is used by createUrl() to prepend to created URLs.

throws yii\base\InvalidConfigException

if running in console application and $baseUrl is not configured.

getBuiltRulesFromCache() protected method (available since version 2.0.14)

Provides the built URL rules that are associated with the $ruleDeclarations from cache.

protected yii\web\UrlRuleInterface[]|false getBuiltRulesFromCache ( $ruleDeclarations )
$ruleDeclarations array

The rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats.

return yii\web\UrlRuleInterface[]|false

The rule objects built from the given rule declarations or boolean false when there are no cache items for this definition exists.

getHostInfo() public method

Returns the host info that is used by createAbsoluteUrl() to prepend to created URLs.

public string getHostInfo ( )
return string

The host info (e.g. http://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs.

throws yii\base\InvalidConfigException

if running in console application and $hostInfo is not configured.

getScriptUrl() public method

Returns the entry script URL that is used by createUrl() to prepend to created URLs.

It defaults to yii\web\Request::$scriptUrl. This is mainly used when $enablePrettyUrl is false or $showScriptName is true.

public string getScriptUrl ( )
return string

The entry script URL that is used by createUrl() to prepend to created URLs.

throws yii\base\InvalidConfigException

if running in console application and $scriptUrl is not configured.

getUrlFromCache() protected method (available since version 2.0.8)

Get URL from internal cache if exists.

See also createUrl().

protected boolean|string getUrlFromCache ( $cacheKey, $route, $params )
$cacheKey string

Generated cache key to store data.

$route string

The route (e.g. site/index).

$params array

Rule params.

return boolean|string

The created URL

init() public method

Initializes UrlManager.

public void init ( )
parseRequest() public method

Parses the user request.

public array|boolean parseRequest ( $request )
$request yii\web\Request

The request component

return array|boolean

The route and the associated parameters. The latter is always empty if $enablePrettyUrl is false. false is returned if the current request cannot be successfully parsed.

setBaseUrl() public method

Sets the base URL that is used by createUrl() to prepend to created URLs.

This is mainly used when $enablePrettyUrl is true and $showScriptName is false.

public void setBaseUrl ( $value )
$value string

The base URL that is used by createUrl() to prepend to created URLs.

setBuiltRulesCache() protected method (available since version 2.0.14)

Stores $builtRules to cache, using $rulesDeclaration as a part of cache key.

protected boolean setBuiltRulesCache ( $ruleDeclarations, $builtRules )
$ruleDeclarations array

The rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats.

$builtRules yii\web\UrlRuleInterface[]

The rule objects built from the given rule declarations.

return boolean

Whether the value is successfully stored into cache

setHostInfo() public method

Sets the host info that is used by createAbsoluteUrl() to prepend to created URLs.

public void setHostInfo ( $value )
$value string

The host info (e.g. "http://www.example.com") that is used by createAbsoluteUrl() to prepend to created URLs.

setRuleToCache() protected method (available since version 2.0.8)

Store rule (e.g. yii\web\UrlRule) to internal cache.

protected void setRuleToCache ( $cacheKey, yii\web\UrlRuleInterface $rule )
$cacheKey
$rule yii\web\UrlRuleInterface
setScriptUrl() public method

Sets the entry script URL that is used by createUrl() to prepend to created URLs.

This is mainly used when $enablePrettyUrl is false or $showScriptName is true.

public void setScriptUrl ( $value )
$value string

The entry script URL that is used by createUrl() to prepend to created URLs.