Yii2 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.
Routing and URL Creation
When a Yii application starts processing a requested URL, the first step it takes is to parse the URL into a route. The route is then used to instantiate the corresponding controller action to handle the request. This whole process is called routing.
The reverse process of routing is called URL creation, which creates a URL from a given route and the associated query parameters. When the created URL is later requested, the routing process can resolve it back into the original route and query parameters.
The central piece responsible for routing and URL creation is the URL manager, which is registered as the urlManager
application component. The URL manager provides the parseRequest()
method to parse an incoming request into a route and the associated query parameters and the createUrl()
method to create a URL from a given route and its associated query parameters.
By configuring the urlManager
component in the application configuration, you can let your application recognize arbitrary URL formats without modifying your existing application code. For example, you can use the following code to create a URL for the post/view
action:
use yii\helpers\Url;
// Url::to() calls UrlManager::createUrl() to create a URL
$url = Url::to(['post/view', 'id' => 100]);
Depending on the urlManager
configuration, the created URL may look like one of the following (or other format). And if the created URL is requested later, it will still be parsed back into the original route and query parameter value.
/index.php?r=post%2Fview&id=100
/index.php/post/100
/posts/100