Home > Backend Development > PHP Tutorial > Yii Framework Official Guide Series 43 - Special Topic: URL (Creation, Routing, Beautification and Customization)

Yii Framework Official Guide Series 43 - Special Topic: URL (Creation, Routing, Beautification and Customization)

黄舟
Release: 2023-03-05 18:56:01
Original
1375 people have browsed it



#Complete URL management of web applications includes two aspects. First, when the user requests the agreed URL, the application needs to parse it into understandable parameters. Second, the application needs to provide a way to create URLs so that the created URLs can be understood by the application. For Yii applications, these are assisted by CUrlManager.

1. Creating URLs

Although URLs can be hard-coded in the controller's view file, they can often be created dynamically with great flexibility:


$url=$this->createUrl($route,$params);
Copy after login

$this refers to the controller instance; $route specifies the requested route requirements; $params lists the requirements attached to the URL GET parameters in .

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

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

The parameters are concatenated with a series of Name=Value symbols. Appearing in the request string, 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 URL look cleaner and more self-explanatory by using the so-called 'path format, omitting the query string and adding the GET parameters to the path information as part of the URL:

/index.php/post/read/id/100
Copy after login

To change the URL format, we should configure the urlManager application element 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',
        ),
    ),
);
Copy after login

Please 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 generates a relative address. In order to get an absolute URL, we can use the prefix yii">. Tip: This URL is a relative address generated by the createurl method. In order 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 path format URL, we can specify certain URL rules make our URLs more user-friendly. For example, we can generate a short URL /post/100 instead of the lengthy /index.php/post/read/id/100 URL creation and parsing through CUrlManager. Specify URL rules.

To specify URL rules, we must set the attributes rules of the urlManager application element:


#

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

These rules are specified as an array of route format pairs, each pair corresponding to a single rule. The route (route) format must be a valid regular expression without delimiters and modifiers. For the path information part of the matching URL, the route should point to a valid route controller. The

rule can bind a small number of GET parameters that appear in the rule format, with a special token. The format is as follows:


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

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

  • urlSuffix: The suffix setting rule used by the URL. The default is null, and the setting of CUrlManager::urlSuffix is ​​used.

  • caseSensitive: Whether the rule is sensitive to large and small schools, the default is null, and the default value of CUrlManager::caseSensitive is used.

  • defaultParams: GET provided by the rule The default value of the parameter (name=>value). When the rule is used to parse the incoming request, the value declared in this attribute will be injected into $_GET.

  • matchValue: When created Whether the value of the GET parameter in a URL matches the corresponding sub-pattern in the rule. The default is null, which means that the value in CUrlManager::matchValue is used. If the attribute value is false, it means that if the route and parameter names match The given match then the rule is used to create a URL. If this property is set to true, then the given parameter value must also match the corresponding subpattern parameter value. Note that if the value of this property is set to true Will reduce performance

Use named parameters

A rule can associate some GET parameters. These GET parameters appear as special tokens in the pattern of the rule, as follows:

<ParamName:ParamPattern>;
Copy after login

ParamName indicates the GET parameter name, and the optional ParamPattern indicates what will be used Regular expression matching GET parameter values. When generating a web address (URL), these parameter tokens will be replaced by the corresponding parameter values; when parsing a URL, the corresponding GET parameters will be generated by parsing the results.

We use some examples to explain the URL working rules. Let's assume that our rules include the following three:


##
array(
    'posts'=>'post/list',
    'post/<id:\d+>'=>'post/read',
    'post/<year:\d{4}>/<title>'=>'post/read',
)
Copy after login

    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.

  • 调用$this->createUrl('post/read',array('year'=>2008,'title'=>'a sample post'))生成/index.php/post/2008/a%20sample%20post。第三个规则适用。

  • 调用$this->createUrl('post/read')产生/index.php/post/read。请注意,没有规则适用。

总之,当使用createUrl生成网址,路线和传递给该方法的GET参数被用来决定哪些网址规则适用。如果关联规则中的每个参数可以在GET参数找到的,将被传递给createUrl ,如果路线的规则也匹配路线参数,规则将用来生成网址。

如果GET参数传递到createUrl是以上所要求的一项规则,其他参数将出现在查询字符串。例如,如果我们调用$this->createUrl('post/read',array('id'=>100,'year'=>2008)) ,我们将获得/index.php/post/100?year=2008。为了使这些额外参数出现在路径信息的一部分,我们应该给规则附加/*。 因此,该规则post/<id:\d+>/* ,我们可以获取网址/index.php/post/100/year/2008 。

正如我们提到的,URL规则的其他用途是解析请求网址。当然,这是URL生成的一个逆过程。例如, 当用户请求/index.php/post/100 ,上面例子的第二个规则将适用来解析路线post/read和GET参数array('id'=>100) (可通过$_GET获得) 。

createurl方法所产生的是一个相对地址。为了得到一个绝对的url ,我们可以用前缀<code>yii">注:使用的URL规则将降低应用的性能。这是因为当解析请求的URL ,[ CUrlManager ]尝试使用每个规则来匹配它,直到某个规则可以适用。因此,高流量网站应用应尽量减少其使用的URL规则。

参数化路由

从版本1.0.5开始, 我们可能会用到命名参数作为路由规则的一部分. 这就允许一个规则可以基于匹配规范被用来匹配多个路由,这也许还会帮助减少应用所需的规则的数目,从而提高整体的性能.

我们使用如下示例规则来说明如何通过命名参数来参数化路由:


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',
)
Copy after login

在上面的示例中, 我们在路由规则中使用了两个命名参数: _c_a. The former matches a controller ID to be either post or comment, while the latter matches an action ID to be createupdate or delete. You may name the parameters differently as long as they do not conflict with GET parameters that may appear in URLs.

使用上面的规则, URL /index.php/post/123/create 将会被解析为 post/create 使用GET参数 id=123. And given the route comment/list and GET parameter page=2, we can create a URL /index.php/comments?page=2.

参数化主机名

从版本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 //m.sbmmt.com/ may be parsed into GET parameters user=admin and lang=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://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',
)
Copy after login

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

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 should NOT contain the sub-folder if the application is under a sub-folder of the Web root. For example, if the application is under //m.sbmmt.com/, then we should still use the same URL rule as described above without the sub-folder sandbox/blog.

隐藏 index.php

还有一点,我们可以做进一步清理我们的网址,即在URL中藏匿index.php入口脚本。这就要求我们配置Web服务器,以及urlManager应用程序元件。

我们首先需要配置Web服务器,这样一个URL没有入口脚本仍然可以处理入口脚本。如果是Apache HTTP server,可以通过打开网址重写引擎和指定一些重写规则。这两个操作可以在包含入口脚本的目录下的.htaccess文件里实现。下面是一个示例:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php
Copy after login

然后,我们设定urlManager元件的showScriptName属性为 false

注意在正式测试之前确保apache开启了rewrite模块,在ubuntu中开启的方式如下:

cd /etc/apache2/mods-enabled

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

sudo service apache2 restart

现在,如果我们调用$this->createUrl('post/read',array('id'=>100)) ,我们将获取网址/post/100。更重要的是,这个URL可以被我们的Web应用程序正确解析。

Faking URL Suffix(伪造URL后缀)

我们还可以添加一些网址的后缀。例如,我们可以用/post/100.html来替代/post/100 。这使得它看起来更像一个静态网页URL。为了做到这一点,只需配置urlManager元件的urlSuffix属性为你所喜欢的后缀。

3. 使用自定义URL规则设置类

注意: Yii从1.1.8版本起支持自定义URL规则类

默认情况下,每个URL规则都通过CUrlManager来声明为一个CUrlRule对象,这个对象会解析当前请求并根据具体的规则来生成URL。 虽然CUrlRule可以处理大部分URL格式,但在某些特殊情况下仍旧有改进余地。

比如,在一个汽车销售网站上,可能会需要支持类似/Manufacturer/Model这样的URL格式, 其中Manufacturer 和 Model 都各自对应数据库中的一个表。此时CUrlRule就无能为力了。

我们可以通过继承CUrlRule的方式来创造一个新的URL规则类。并且使用这个类解析一个或者多个规则。 以上面提到的汽车销售网站为例,我们可以声明下面的URL规则。


array(
    // 一个标准的URL规则,将 '/' 对应到 'site/index'
    '' => 'site/index',

    // 一个标准的URL规则,将 '/login' 对应到 'site/login', 等等
    '<action:(login|logout|about)>' => 'site/<action>',

    // 一个自定义URL规则,用来处理 '/Manufacturer/Model'
    array(
        'class' => 'application.components.CarUrlRule',
        'connectionID' => 'db',
    ),

    // 一个标准的URL规则,用来处理 'post/update' 等
    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
Copy after login

从以上可以看到,我们自定义了一个URL规则类CarUrlRule来处理类似/Manufacturer/Model这样的URL规则。 这个类可以这么写:


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
    }
}
Copy after login

自定义URL规则类必须实现在CBaseUrlRule中定义的两个接口。

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

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

除了这种典型用法,自定义URL规则类还可以有其他的用途。比如,我们可以写一个规则类来记录有关URL解析和UEL创建的请求。 这对于正在开发中的网站来说很有用。我们还可以写一个规则类来在其他URL规则都匹配失败的时候显示一个自定义404页面。 注意,这种用法要求规则类在所有其他规则的最后声明。

 以上就是Yii框架官方指南系列43——专题:URL(创建、路由、美化及自定义)的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template