Yii Framework official guide series 43-topics: URL (creation, routing, beautification and customization)

Source: Internet
Author: User
The complete URL management of Web applications includes two aspects. First, when a user requests a specified URL, the application needs to parse it into understandable parameters. Second, the application needs to provide a method to create a URL for creating a URL...

The complete URL management of Web applications includes two aspects. First, when a user requests a specified URL, the application needs to parse it into understandable parameters. Second, the application needs to provide a method to create a URL so that the created URL application can understand it. For Yii applications, these are done with CUrlManager assistance.

1. Creating URLs (create URL)

Although URLs can be hard-coded in the controller's view files, they can be dynamically created flexibly:


$ This refers to the controller instance; $ route specifies the request's route requirements; $ params listsGETParameters.

By default, URLs are created using createUrl in get format. For example, if $ route = 'post/read' and $ params = array ('id' => 100) are provided, we will get the following URL:


Parameters are concatenated by a series of Name = values in the request string. the r parameter refers to the requested route. This URL format is not user-friendly because it requires some non-character characters.

We can make the above URL look more concise and self-explanatory. by using the so-called 'path' format, we can save the query string and add the GET parameter to the path information as part of the URL:


To change the URL format, we should configure the urlManager application component so that createUrl can automatically switch to the new format and the application can correctly understand the new URL:

array(    ......    'components'=>array(        ......        'urlManager'=>array(            'urlFormat'=>'path',        ),    ),);

Note that we do not need to specify the urlManager component class because it is pre-declared as CUrlManager in CWebApplication.

The createurl method generates a relative address. To get an absolute url, we can use the prefix yii ">Tip: The createurl method generates a relative address. To get an absolute url, we can use the prefix yii:: App ()-> hostInfo, or call createAbsoluteUrl.

2. User-friendly URLs (user-friendly URL)

When using the path format URL, we can specify some URL rules to make our URL more user-friendly. For example, we can generate a short URL/post/100 instead of lengthy/index. php/post/read/id/100. You can use CUrlManager to specify URL rules for URL creation and resolution.

To specify the URL rule, we must set the attribute rules of the urlManager application component:

array(    ......    'components'=>array(        ......        'urlManager'=>array(            'urlFormat'=>'path',            'rules'=>array(                'pattern1'=>'route1',                'pattern2'=>'route2',                'pattern3'=>'route3',            ),        ),    ),);

These rules are specified for arrays in a series of route formats, and each pair corresponds to a single rule. The format of the route must be a valid regular expression without separators or modifiers. It is used to match the URL information. Also, route should point to a valid route controller.

A rule can bind a small number of GET parameters. These GET parameters that appear in the Rule format are shown in a special token format as follows:

'pattern1'=>array('route1', 'urlSuffix'=>'.xml', 'caseSensitive'=>false)

The preceding array contains a series of custom options. in version 1.1.0, the following options are valid:

  • UrlSuffix: the suffix setting rule used by the URL. the default value is null and the setting of CUrlManager: urlSuffix is used.

  • CaseSensitive: whether the rule is sensitive to primary school. the default value is null and the default value of CUrlManager: caseSensitive is used.

  • DefaultParams: default value of the GET parameter provided by the rule (name => value). when the rule is used to parse the input request, the value declared in this attribute will be injected with $ _ GET.

  • MatchValue: whether the value of the GET parameter matches the corresponding sub-pattern in the rule when a URL is created. the default value is null, which means that the value in CUrlManager: matchValue is used. if the attribute value is false, this rule is used to create a URL if the route and parameter names match the given one. if this attribute is set to true, the given parameter value must match the value of the corresponding sub-mode parameter. note: setting this attribute to true will reduce the performance.

Use named parameters

A rule can be associated with some GET parameters. These GET parameters appear as special tokens in the rule mode, as shown below:


ParamNameThe GET parameter name. optional.ParamPatternThe regular expression that matches the GET parameter value. When a URL is generated, these parameter tokens are replaced by the corresponding parameter values. when a URL is parsed, the corresponding GET parameter is generated by parsing the result.

We use some examples to explain the website work rules. Assume that our rules include the following:

Array ('posts' => 'Post/list', 'post/
'=> 'Post/read', 'post/
   '=> 'Post/read',) </pre>

  • Call$this->createUrl('post/list')Generate/index.php/posts. The first rule applies.

  • Call$this->createUrl('post/read',array('id'=>100))Generate/index.php/post/100. The second rule applies.

  • Call$this->createUrl('post/read',array('year'=>2008,'title'=>'a sample post'))Generate/index.php/post/2008/a%20sample%20post. The third rule applies.

  • Call$this->createUrl('post/read')Generate/index.php/post/read. Note that no rules apply.

In short, when you use createUrl to generate a URL, the route and GET parameters passed to this method are used to determine which URL rules apply. If each parameter in the association rule can be found in the GET parameter, it will be passed to createUrl. if the route rule matches the route parameter, the rule will be used to generate a URL.

If the GET parameter is passed to createUrl as a rule described above, other parameters will appear in the query string. For example, if we call$this->createUrl('post/read',array('id'=>100,'year'=>2008)), We will get/index.php/post/100?year=2008. To make these extra parameters appear in part of the path information, we should attach the rule/*. Therefore, this rulepost/ /* , We can get the URL/index.php/post/100/year/2008.

As we mentioned, other purposes of URL rules are to parse the request URL. Of course, this is an inverse process of URL generation. For example, when a user requests/index.php/post/100, The second rule in the above example will apply to parse the routepost/readAnd GET parametersarray('id'=>100)(You can use$_GET).

The createurl method generates a relative address. To get an absolute url, we can use the prefixyii">Note: The URL rules used will reduce the application performance. This is because when the request URL is parsed, [CUrlManager] tries to use each rule to match it until a rule can apply. Therefore, high-traffic website applications should minimize the URL rules they use.

Parameterized routing

Starting from version 1.0.5, we may use named parameters as part of routing rules. this allows a rule to be used to match multiple routes based on the matching rules. This may also help reduce the number of rules required by the application and improve the overall performance.

The following sample rules are used to describe how to parameterize a route using named parameters:

array(    '<_c:(post|comment)>/
     /<_a:(create|update|delete)>' => '<_c>/<_a>',    '<_c:(post|comment)>/
      ' => '<_c>/read',    '<_c:(post|comment)>s' => '<_c>/list',)

In the preceding example, two named parameters are used in the routing rules:_cAnd_a. The former matches a controller ID to be eitherpostOrcomment, While the latter matches an action ID to becreate,updateOrdelete. You may name the parameters differently as long as they do not conflict with GET parameters that may appear in URLs.

Use the above rule, URL/index.php/post/123/createWill be parsedpost/createUse GET parametersid=123. And given the routecomment/listAnd GET parameterpage=2, We can create a URL/index.php/comments?page=2.

Parameterized host name

Starting from version 1.0.11, it is also possible to include hostname into the rules for parsing and creating URLs. One may extract part of the hostname to be a GET parameter. For example, the URL#May be parsed into GET parametersuser=adminAndlang=en. On the other hand, rules with hostname may also be used to create URLs with paratermized hostnames.

In order to use parameterized hostnames, simply declare URL rules with host info, e.g .:

array(    'http://
      /profile' => 'user/profile',)

The above example says that the first segment in the hostname shocould be treateduserParameter while the first segment in the path info shocould belangParameter. The rule corresponds touser/profileRoute.

Note that CUrlManager: showScriptName will not take effect when a URL is being created using a rule with parameterized hostname.

Also note that the rule with parameterized hostname shoshould NOT contain in the sub-folder if the application is under a sub-folder of the Web root. For example, if the application is under#, Then we shoshould still use the same URL rule as described abve without the sub-foldersandbox/blog.

Hide index.php

In addition, we can further clean up our website, that is, hiding in the URLindex.phpPortal script. This requires us to configure the Web server and urlManager application components.

First, we need to configure the Web server so that a URL can still process the portal script without an entry script. For Apache HTTP server, you can enable the URL rewriting engine and specify some rewrite rules. These two operations can be performed in the directory containing the script entry.htaccessFile. The following is an example:

Options +FollowSymLinksIndexIgnore */*RewriteEngine on# if a directory or a file exists, use it directlyRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d# otherwise forward it to index.phpRewriteRule . index.php

Then, we set the showScriptName attribute of the urlManager componentfalse.

Make sure that the rewrite module is enabled for apache before the formal test. the method for enabling the rewrite module in ubuntu is as follows:


Sudo ln-s ../mod-available/rewrite. load rewrite. load

Sudo service apache2 restart

Now, if we call$this->createUrl('post/read',array('id'=>100)), We will get the URL/post/100. More importantly, this URL can be correctly parsed by our Web application.

Faking URL Suffix (forged URL Suffix)

We can also add some URLs with suffixes. For example, we can use/post/100.htmlTo replace/post/100. This makes it look more like a static webpage URL. To do this, you only need to configure the urlSuffix attribute of the urlManager component as your preferred suffix.

3. use custom URL rules to set classes

Note:Yii supports custom URL rules from version 1.1.8.

By default, each URL rule is declared as a CUrlRule object through CUrlManager. this object will parse the current request and generate a URL based on the specific rules. Although CUrlRule can process most URL formats, there is still room for improvement in some special cases.

For example, a car sales website may need to support similar/Manufacturer/ModelIn this URL formatManufacturerAndModelEach corresponding to a table in the database. At this time, CUrlRule is powerless.

We can create a new URL rule class by inheriting CUrlRule. Use this class to parse one or more rules. For example, we can declare the following URL rules.

Array (// A standard URL rule, maps '/' to 'site/index''' => 'site/Index', // A standard URL rule, maps '/login' to 'site/login', and so on' => 'site/'. // A Custom URL rule, used to process '/Manufacturer/model' array ('class' => 'application. components. carUrlRule ', 'connectionid' => 'DB',), // A standard URL rule for processing 'post/Update', etc'

We can see from the above that we have customized a URL rule classCarUrlRuleTo handle similar/Manufacturer/ModelSuch a URL rule. This class can be written as follows:

class CarUrlRule extends CBaseUrlRule{    public $connectionID = 'db';    public function createUrl($manager,$route,$params,$ampersand)    {        if ($route==='car/index')        {            if (isset($params['manufacturer'], $params['model']))                return $params['manufacturer'] . '/' . $params['model'];            else if (isset($params['manufacturer']))                return $params['manufacturer'];        }        return false;  // this rule does not apply    }    public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)    {        if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches))        {            // check $matches[1] and $matches[3] to see            // if they match a manufacturer and a model in the database            // If so, set $_GET['manufacturer'] and/or $_GET['model']            // and return 'car/index'        }        return false;  // this rule does not apply    }}

The custom URL rule class must implement the two interfaces defined in CBaseUrlRule.

  • [CBaseUrlRule: createUrl () | createUrl ()]

  • [CBaseUrlRule: parseUrl () | parseUrl ()]

In addition to this typical usage, the custom URL rule class can also be used for other purposes. For example, we can write a rule class to record URL resolution and UEL creation requests. This is useful for developing websites. We can also write a rule class to display a custom 404 page when all other URL rules fail to match. Note that this usage requires the rule class to be declared at the end of all other rules.

The above is the Yii Framework official guide series 43 -- special topic: URL (creation, routing, beautification and customization) content. For more information, see PHP Chinese network (www.php1.cn )!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.