UrlManager
API reference › yii › web › UrlManager
UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
UrlManager is configured as an application component in 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 UrlRuleInterface, by default that is UrlRule.
For nesting rules, there is also a GroupUrlRule class.
For more details and usage information on UrlManager, see the guide article on routing.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$baseUrl | string | The base URL that is used by createUrl() to prepend to created URLs. | UrlManager |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$cache | yii\| | The cache object or the application component ID of the cache object. Default: 'cache'. | UrlManager |
$enablePrettyUrl | bool | Whether to enable pretty URLs. Default: false. | UrlManager |
$enableStrictParsing | bool | Whether to enable strict parsing. Default: false. | UrlManager |
$hostInfo | string | The host info (e.g. https://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs. | UrlManager |
$normalizer | UrlNormalizer| | The configuration for UrlNormalizer used by this UrlManager. Default: false. Available since 2.0.10. | UrlManager |
$routeParam | string | The GET parameter name for route. Default: 'r'. | UrlManager |
$ruleConfig | array | The default configuration of URL rules. Default: ['class' => 'yii\. | UrlManager |
$rules | array | The rules for creating and parsing URLs when $enablePrettyUrl is true. Default: []. | UrlManager |
$scriptUrl | string | The entry script URL that is used by createUrl() to prepend to created URLs. | UrlManager |
$showScriptName | bool | Whether to show entry script name in the constructed URL. Default: true. | UrlManager |
$suffix | string | The URL suffix used when $enablePrettyUrl is true. Default: null. | UrlManager |
$cacheKey protected | string | The cache key for cached rules Default: __CLASS__. Available since 2.0.8. | UrlManager |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
addRules() | Adds additional URL rules. | UrlManager |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
createAbsoluteUrl() | Creates an absolute URL using the given route and query parameters. | UrlManager |
createUrl() | Creates a URL using the given route and query parameters. | UrlManager |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getBaseUrl() | Returns the base URL that is used by createUrl() to prepend to created URLs. | UrlManager |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getHostInfo() | Returns the host info that is used by createAbsoluteUrl() to prepend to created URLs. | UrlManager |
getScriptUrl() | Returns the entry script URL that is used by createUrl() to prepend to created URLs. | UrlManager |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes UrlManager. | UrlManager |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
parseRequest() | Parses the user request. | UrlManager |
setBaseUrl() | Sets the base URL that is used by createUrl() to prepend to created URLs. | UrlManager |
setHostInfo() | Sets the host info that is used by createAbsoluteUrl() to prepend to created URLs. | UrlManager |
setScriptUrl() | Sets the entry script URL that is used by createUrl() to prepend to created URLs. | UrlManager |
trigger() | Triggers an event. | yii\ |
buildRules() protected | Builds URL rule objects from the given rule declarations. | UrlManager |
canBeCached() protected | Returns the value indicating whether result of createUrl() of rule should be cached in internal cache. | UrlManager |
getBuiltRulesFromCache() protected | Provides the built URL rules that are associated with the $ruleDeclarations from cache. | UrlManager |
getUrlFromCache() protected | Get URL from internal cache if exists. | UrlManager |
setBuiltRulesCache() protected | Stores $builtRules to cache, using $rulesDeclaration as a part of cache key. | UrlManager |
setRuleToCache() protected | Store rule (e.g. UrlRule) to internal cache. | UrlManager |
Property details
Section titled “Property details”$cache
Section titled “$cache ”public yii\caching\CacheInterface|array|string|bool|null $cache = 'cache'The cache object or the application component ID of the cache object.
This can also be an array that is used to create a 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.
$enablePrettyUrl
Section titled “$enablePrettyUrl ”public bool $enablePrettyUrl = falseWhether 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”.
$enableStrictParsing
Section titled “$enableStrictParsing ”public bool $enableStrictParsing = falseWhether 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.
$normalizer
Section titled “$normalizer ”public yii\web\UrlNormalizer|array|string|false $normalizer = falseThe configuration for 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,]Since
2.0.10
$routeParam
Section titled “$routeParam ”public string $routeParam = 'r'The GET parameter name for route.
This property is used only if $enablePrettyUrl is false.
$ruleConfig
Section titled “$ruleConfig ”public array $ruleConfig = ['class' => 'yii\web\UrlRule']The default configuration of URL rules.
Individual rule configurations
specified via $rules will take precedence when the same property of the rule is configured.
$rules
Section titled “$rules ”public array $rules = []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.
$showScriptName
Section titled “$showScriptName ”public bool $showScriptName = trueWhether to show entry script name in the constructed URL.
Defaults to true.
This property is used only if $enablePrettyUrl is true.
$suffix
Section titled “$suffix ”public string $suffix = nullThe 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.
Method details
Section titled “Method details”addRules()
Section titled “addRules() ”public function addRules(array $rules, bool $append = true): mixedAdds 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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 | bool | Whether to add the new rules by appending them to the end of the existing rules. |
Returns
mixed
createAbsoluteUrl()
Section titled “createAbsoluteUrl() ”public function createAbsoluteUrl(string|array $params, string|null $scheme = null): stringCreates an absolute URL using the given route and query parameters.
This method prepends the URL created by createUrl() with the $hostInfo.
Note that unlike Url::toRoute(), this method always treats the given route
as an absolute route.
Parameters
| Parameter | Type | Description |
|---|---|---|
$params | string| | 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',). |
$scheme | string| | 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. |
Returns
string: The created URL
See also
createUrl()
Section titled “createUrl() ”public function createUrl(string|array $params): stringCreates 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¶m1=value1¶m2=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¶m1=value1#name['site/index', 'param1' => 'value1', '#' => 'name']The URL created is a relative one. Use createAbsoluteUrl() to create an absolute URL.
Note that unlike Url::toRoute(), this method always treats the given route
as an absolute route.
Parameters
| Parameter | Type | Description |
|---|---|---|
$params | string| | 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',). |
Returns
string: The created URL
getBaseUrl()
Section titled “getBaseUrl() ”public function getBaseUrl(): stringReturns the base URL that is used by createUrl() to prepend to created URLs.
It defaults to Request::$baseUrl.
This is mainly used when $enablePrettyUrl is true and $showScriptName is false.
Returns
string: The base URL that is used by createUrl() to prepend to created URLs.
Throws
yii\base\InvalidConfigException: if running in console application and$baseUrlis not configured.
getHostInfo()
Section titled “getHostInfo() ”public function getHostInfo(): stringReturns the host info that is used by createAbsoluteUrl() to prepend to created URLs.
Returns
string: The host info (e.g. https://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs.
Throws
yii\base\InvalidConfigException: if running in console application and$hostInfois not configured.
getScriptUrl()
Section titled “getScriptUrl() ”public function getScriptUrl(): stringReturns the entry script URL that is used by createUrl() to prepend to created URLs.
It defaults to Request::$scriptUrl.
This is mainly used when $enablePrettyUrl is false or $showScriptName is true.
Returns
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$scriptUrlis not configured.
parseRequest()
Section titled “parseRequest() ”public function parseRequest(yii\web\Request $request): array|boolParses the user request.
Parameters
| Parameter | Type | Description |
|---|---|---|
$request | Request | The request component |
Returns
array|bool: 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()
Section titled “setBaseUrl() ”public function setBaseUrl(string $value): mixedSets 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The base URL that is used by createUrl() to prepend to created URLs. |
Returns
mixed
setHostInfo()
Section titled “setHostInfo() ”public function setHostInfo(string $value): mixedSets the host info that is used by createAbsoluteUrl() to prepend to created URLs.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The host info (e.g. “https://www.example.com”) that is used by createAbsoluteUrl() to prepend to created URLs. |
Returns
mixed
setScriptUrl()
Section titled “setScriptUrl() ”public function setScriptUrl(string $value): mixedSets 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The entry script URL that is used by createUrl() to prepend to created URLs. |
Returns
mixed
buildRules()
Section titled “buildRules() ”protected function buildRules(array $ruleDeclarations): yii\web\UrlRuleInterface[]Builds URL rule objects from the given rule declarations.
Parameters
| Parameter | Type | Description |
|---|---|---|
$ruleDeclarations | array | The rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats. |
Returns
UrlRuleInterface[]: The rule objects built from the given rule declarations
Throws
yii\base\InvalidConfigException: if a rule declaration is invalid
canBeCached()
Section titled “canBeCached() ”protected function canBeCached(yii\web\UrlRuleInterface $rule): boolReturns the value indicating whether result of createUrl() of rule should be cached in internal cache.
Parameters
| Parameter | Type | Description |
|---|---|---|
$rule | UrlRuleInterface |
Returns
bool: true if result should be cached, false if not.
Since
2.0.12
See also
getBuiltRulesFromCache()
Section titled “getBuiltRulesFromCache() ”protected function getBuiltRulesFromCache(array $ruleDeclarations): yii\web\UrlRuleInterface[]|falseProvides the built URL rules that are associated with the $ruleDeclarations from cache.
Parameters
| Parameter | Type | Description |
|---|---|---|
$ruleDeclarations | array | The rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats. |
Returns
UrlRuleInterface[]|false: The rule objects built from the given rule declarations or boolean false when there are no cache items for this definition exists.
Since
2.0.14
getUrlFromCache()
Section titled “getUrlFromCache() ”protected function getUrlFromCache(string $cacheKey, string $route, array $params): bool|stringGet URL from internal cache if exists.
Parameters
| Parameter | Type | Description |
|---|---|---|
$cacheKey | string | Generated cache key to store data. |
$route | string | The route (e.g. site/index). |
$params | array | Rule params. |
Returns
bool|string: The created URL
Since
2.0.8
See also
setBuiltRulesCache()
Section titled “setBuiltRulesCache() ”protected function setBuiltRulesCache(array $ruleDeclarations, yii\web\UrlRuleInterface[] $builtRules): boolStores $builtRules to cache, using $rulesDeclaration as a part of cache key.
Parameters
| Parameter | Type | Description |
|---|---|---|
$ruleDeclarations | array | The rule declarations. Each array element represents a single rule declaration. Please refer to $rules for the acceptable rule formats. |
$builtRules | UrlRuleInterface[] | The rule objects built from the given rule declarations. |
Returns
bool: Whether the value is successfully stored into cache
Since
2.0.14
setRuleToCache()
Section titled “setRuleToCache() ”protected function setRuleToCache(mixed $cacheKey, yii\web\UrlRuleInterface $rule): mixedStore rule (e.g. UrlRule) to internal cache.