Yii Framework Official Guide Series 43--topic: URL (Create, route, beautify, and customize)

Source: Internet
Author: User



The full URL management of a Web application consists of two facets. First, when the user requests the URL of the contract, the application needs to parse it into an understandable parameter. Second, application requirements provide a way to create URLs in order to create URLs that the application can understand. For YII applications, these are done through curlmanager assistance.

1. Creating URLs (Create URLs)

Although URLs can be hard-coded in the view files of a controller, they can often be flexibly created dynamically:


$url = $this->createurl ($route, $params);

$this refers to the controller instance; $route Specify the requirements for the requested route, $params lists the parameters attached to the URL GET .

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

/index.php?r=post/read&id=100

Parameters are concatenated together in a series of name=value by symbols in the request string, and the R parameter refers to the requested route. This URL format is not very user friendly, because it requires some non-word characters.

We can make the above URLs look cleaner and more self-explanatory by using the so-called ' path ' format, omitting the query string and adding the get parameter to the path information as part of the URL:

/index.php/post/read/id/100

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 class of the Urlmanager element, because it is pre-declared as Curlmanager in Cwebapplication.

The CreateURL method produces a relative address. To get an absolute URL, we can use the prefix yii "> hint: This URL is generated by the CreateURL method as 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 URLs)

When using the path format URL, we can specify certain URL rules to make our URLs more user-friendly. For example, we can produce a short url/post/100, not a lengthy/index.php/post/read/id/100. URL creation and parsing are all specified by Curlmanager URL rules.

To specify the URL rule, we must set the properties of the Urlmanager application symbol rules:


Array (...    ') Components ' =>array (...        ') Urlmanager ' =>array (            ' urlformat ' = ' path ',            ' rules ' =>array (                ' pattern1 ' = ' route1 ',                ' Pattern2 ' = ' route2 ', ' pattern3 ' = ' route3 ',),),)    ;

These rules are specified in a series of route formats, each pair corresponds to a single rule. The route format must be a valid regular expression, with no delimiters and modifiers. It is a part of the path information used to match URLs. And the 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 represented in a special token format as follows:


' Pattern1 ' =>array (' route1 ', ' urlsuffix ' = '. Xml ', ' CaseSensitive ' =>false)

The above array contains a set of custom option settings, in version 1.1.0, the following options are valid:

    • The suffix setting rule used by the Urlsuffix:url is null by default and is used with the Curlmanager::urlsuffix setting.

    • CaseSensitive: Whether the rule is sensitive to large primary schools, the default is null, and the default value of Curlmanager::casesensitive is used.

    • Defaultparams: The 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 the attribute is injected into the $_get.

    • Matchvalue: When creating a URL, the value of the get parameter matches the corresponding sub-pattern in the rule. The default is null, which means that the value in Curlmanager::matchvalue is used. If the property value is false, it means that the rule is used to create a URL if the route and parameter names match the given matches. If the property is set to True, the given parameter value must also match the corresponding sub-mode parameter value. Note If setting the value of this property to true will degrade performance

Using named parameters

A rule can associate some get parameters. These get parameters appear as special tokens in the rule's pattern, as follows:

<ParamName:ParamPattern>;

ParamNameRepresents the Get parameter name, optionally ParamPattern representing the regular expression that will be used to match the get parameter value. When a URL is generated, these parameter tokens are replaced by the corresponding parameter values, and when a URL is parsed, the corresponding get parameters are generated by parsing the result.

We use some examples to explain the Web site work rules. We assume that our rules include the following three:


Array (    ' posts ' = ' post/list ',    ' post/<id:\d+> ' = ' post/read ',    ' post/<year:\d{4}>/ <title> ' = ' post/read ',)

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

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

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

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

In summary, when using CreateURL to generate URLs, alignments and the get parameters passed to the 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, and if the alignment rules also match the alignment parameters, the rule will be used to generate the URL.

If the get parameter is passed to CreateURL is one of the rules required above, additional 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 . In order for these additional parameters to appear as part of the path information, we should append the rules /* . So, the rule post/<id:\d+>/* , we can get URLs /index.php/post/100/year/2008 .

As we mentioned, the other purpose of the URL rule is to parse the request URL. Of course, this is a reverse process of URL generation. For example, when the user requests /index.php/post/100 , the second rule in the example above will be applied to parse the route post/read and get Parameters array('id'=>100) (available by $_GET acquisition).

The CreateURL method produces a relative address. In order to get an absolute URL, we can use yii"> the prefix Note: The URL rules used will degrade the performance of the application. This is because when the URL of the request is parsed, [Curlmanager] attempts to match it with each rule until a rule can be applied. Therefore, high-traffic site applications should minimize the URL rules they use.

Parameterized routing

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

We use the following example rules to illustrate how to parameterize routes with named parameters:


Array (    ' <_c: (post|comment) >/<id:\d+>/<_a: (create|update|delete) > ' = ' <_c>/<_a > ',    ' <_c: (post|comment) >/<id:\d+> ' = ' <_c>/read ',    ' <_c: (post|comment) >s ' = > ' <_c>/list ',)

In the example above, we used two named parameters in the routing rule: _c and _a . The former matches a controller ID to is either post or comment , while the latter matches an action ID to be create , update o R. May delete name the parameters differently as long as they does not conflict with GET parameters that could appear in UR Ls.

Using the rules above, the URL /index.php/post/123/create will be parsed to post/create use the Get parameter id=123 . And given the route comment/list and GET parameter page=2 , we can create a URL /index.php/comments?page=2 .

Parameterized host Name

Starting with 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 is http://www.php.cn/ parsed into GET parameters and user=admin lang=en . On the other hand, rules with hostname may also is used to create URLs with paratermized hostnames.

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


Array (    ' http://<user:\w+>.example.com/<lang:\w+>/profile ' = ' user/profile ',)

The above example says, the first segment in the hostname should is treated as parameter while the first user segment In the path info should is lang parameter. The rule corresponds to the user/profile route.

Note that Curlmanager::showscriptname would not take effect when a URL was being created using a rule with parameterized hos Tname.

Also Note that the rule with parameterized hostname should not contain the sub-folder if the application is under a SUB-FO Lder of the Web root. For example, if the application are under http://www.php.cn/ , then we should still use the same URL rule as described above without the Sub-Folder sandbox/blog .

Hideindex.php

Also, we can do a further cleanup of our URLs by hiding the portal script in the URL index.php . This requires that we configure the Web server, as well as the Urlmanager application components.

We first need to configure the Web server so that a URL without a portal script can still handle the portal script. If it is Apache HTTP server, you can rewrite the engine by opening the URL and specify some rewrite rules. These two operations can be implemented in a file that contains the entry script in the directory .htaccess . Here is an example:

Options +followsymlinksindexignore */*rewriteengine on# If a directory or a file exists, use it directlyrewritecond%{requ Est_filename}!-frewritecond%{request_filename}!-d# otherwise forward it to index.phprewriterule. index.php

We then set the Showscriptname property of the Urlmanager element to be false .

Note Before formal testing, make sure that Apache opens the rewrite module, which is opened in Ubuntu in the following way:

Cd/etc/apache2/mods-enabled

sudo ln-s. /mods-available/rewrite.load Rewrite.load

sudo service apache2 restart

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

Faking URL Suffix (forged URL suffix)

We can also add suffixes for some URLs. For example, we can use /post/100.html them instead /post/100 . This makes it look more like a static Web page URL. To do this, simply configure the Urlsuffix attribute of the Urlmanager element to the suffix you like.

3. Setting up classes with custom URL rules

Note: Yii supports custom URL rule classes from version 1.1.8

By default, each URL rule is declared as a Curlrule object through curlmanager, which resolves the current request and generates a URL based on a specific rule. Although curlrule can handle most URL formats, there are some special cases where there is still room for improvement.

For example, on a car sales site, you might need to support /Manufacturer/Model a URL format like this, where each Manufacturer Model corresponds to a table in the database. At this time curlrule can do nothing.

We can create a new URL rule class by inheriting curlrule. and use this class to parse one or more rules. As an example of the car sales website mentioned above, we can declare the following URL rules.


Array (    //A standard URL rule that will '/' correspond to ' site/index ' '    = ' = ' site/index ',    //A standard URL rule that will '/login ' correspond to ' site/login ' , et cetera    ' <action: (login|logout|about) > ' = ' site/<action> ',    //A custom URL rule to handle '/manufacturer/ The Model '    array ' (        ' class ' = ' Application.components.CarUrlRule ',        ' connectionid ' = ' = ' db '    ),    //A standard URL rule to handle ' post/update ' <controller:\w+>/<action:\w+> ' = '    <controller>/ <action> ',),

As you can see from the above, we have customized a URL rule class CarUrlRule to handle /Manufacturer/Model URL rules like this. This class can be written like this:


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 isn't 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    }}

A custom URL rule class must implement the two interfaces defined in Cbaseurlrule.

    • [Cbaseurlrule::createurl () |createurl ()]

    • [Cbaseurlrule::p Arseurl () |parseurl ()]

In addition to this typical usage, custom URL rule classes can have other uses. For example, we can write a rule class to record requests for URL parsing and uel creation. This is useful for Web sites that are under development. We can also write a rule class to display a custom 404 page when the other URL rules fail. 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--topic: URL (Create, route, beautify and custom) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.