This article will introduce a method to automatically disconnect a URL route.
This article will introduce a method to automatically disconnect a URL route.
We specify that Yii uses URL manager to support URL creation and resolution. However, the default method is not satisfactory for the routing of mixed words. For example, the URL manager generates the createAccount:
/user/createAccount
This is unfriendly to SEO. What they want is easier to renew like user/create-account. To implement it, we can add the following content to the URL manager rules:
'user/create-account' => 'user/createAccount'
This is a good practice, but it is not the final solution, because we need to specify a rule for each similar route. To avoid trouble and improve performance, we can use the following content extension CUrlManager:
Class UrlManager extends CUrlManager {public $ showScriptName = false; public $ appendParams = false; public $ useStrictParsing = true; public $ urlSuffix = '/'; public function createUrl ($ route, $ params = array (), $ ampersand = '&') {$ route = preg_replace_callback ('/(?
We have defined a CUrlManager subclass UrlManager above. We mainly cover the createUrl () and parseUrl () methods to achieve the broken word routing. We also overwrite the default values of several attributes in CUrlManager to make our URL more friendly.
Now we need to make some minor changes in the application configuration file:
return array( // .... 'components' => array( 'urlManager' => array( 'class' => 'UrlManager', 'rules' => array( // .... '
/' => '
/', ), ), ), );
In the above code, we specify the urlManager class as our new class UrlManager. We also modified some rules so that we can match the hyphen (-) in the URL (by default, only matching words do not match the hyphen ).
With the above settings, we will obtain the URL/user/create-account/for the route user/createAccount /. The last Slash is because we set urlSuffix to/in UrlManager /.
Note: Because the above code uses anonymous functions and lcfirst (), this method runs in PHP 5.3 or later.
This article translated from foreign language website, view the original, please click: http://www.yiiframework.com/wiki/404/hyphenation-of-routes-in-url-management/