Yii框架官方指南系列43-專題:URL(創建、路由、美化及自訂)

黄舟
發布: 2023-03-05 18:56:01
原創
1308 人瀏覽過



Web應用程式完整的URL管理包括兩個方面。首先, 當使用者請求約定的URL,應用程式需要解析 它變成可以理解的參數。第二,應用程式需求提供一種創造URL的方法,以便創建的URL應用程式可以理解的。對於Yii應用程序,這些透過CUrlManager輔助完成。

1. Creating URLs(創建網址)

雖然URL可被硬編碼在控制器的視圖(view)文件,但往往可以很靈活地動態創建它們:


$url=$this->createUrl($route,$params);
登入後複製

/index.php?r=post/read&id=100
登入後複製

/index.php/post/read/id/100
登入後複製


array(
    ......
    'components'=>array(
        ......
        'urlManager'=>array(
            'urlFormat'=>'path',
        ),
    ),
);
登入後複製

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

'pattern1'=>array('route1', 'urlSuffix'=>'.xml', 'caseSensitive'=>false)
登入後複製

<ParamName:ParamPattern>;
登入後複製

array(
    'posts'=>'post/list',
    'post/<id:\d+>'=>'post/read',
    'post/<year:\d{4}>/<title>'=>'post/read',
)
登入後複製


指的是控制器實例; $route指定請求的route 的要求;$params列出了附加在網址中的

GET

參數。

預設情況下,URL以get格式使用createUrl建立。例如,提供$route='post/read'和$params=array('id'=>100) ,我們將取得下列網址:

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',
)
登入後複製
登入後複製

參數以一系列Name=Value透過符號串連起來出現在請求字串,r參數指的是請求的route 。這種URL格式使用者友善性不是很好,因為它需要一些非字元。

    我們可以使上述網址看起來更簡潔,更不言自明,通過採用所謂的'path格式,省去查詢字符串和把GET參數加到路徑信息,作為網址的一部分:
  • array(
        'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',
    )
    登入後複製
    登入後複製

    要更改URL格式,我們應該配置urlManager應用程式元件,以便createUrl可以自動切換到新格式和應用程式可以正確理解新的網址:

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
登入後複製
登入後複製
  • 請注意,我們不需要指定的urlManager元件的類,因為它元件的類,因為它在CWebApplication預先宣告為CUrlManager。
  • createurl方法所產生的是一個相對位址。為了得到一個絕對的url ,我們可以用前綴yii">

    提示:此網址透過createurl方法所產生的是一個相對位址。為了得到一個絕對的url ,我們可以用前綴yii:
  • :app()-> hostInfo ,或呼叫createAbsoluteUrl 。一個短短的URL/post/100 ,而不是冗長/index.php/post/read/id/100。 urlManager 應用元件的屬性rules:

    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>',
    ),
    登入後複製
    登入後複製
    這些規則以一系列的路線格式對數組指定,每對對應於一個單一的規則。式,沒有分隔符號和修飾語。參數,以一種特殊令牌格式表現如下:


    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
        }
    }
    登入後複製
    登入後複製

    上面的數組包含了一系列自定義的選項設置,在版本1.1.0中,下面的選項是有效的:

    • urlSuffix: URL所使用的後綴設定規則,預設是null,使用的是CUrlManager::urlSuffix的設定.

      caseSensitive: 規則是否是大小學敏感的,預設是null,使用的是null,使用的是null,使用的是:caseSensitive的預設值.

    • defaultParams: 規則提供的GET參數的預設值(name=>value). 當規則用來解析輸入請求的時候,該屬性中宣告的值將會注入$_GET.

      matchValue: 當建立一個URL的時候GET參數的值是否和規則中對應的子模式相符. 預設是null, 表示使用的是CUrlManager::matchValue中的值. 如果屬性值是false, 意味著如果路由和參數名稱與給定的匹配那麼該規則被用來創建一個URL. 如果該屬性被設置為true,那麼給定的參數值一定也要和相應的子模式參數值相匹配. 注意如果設定此屬性的值為true將會降低效能

      🎜🎜使用命名參數🎜🎜一個規則可以關聯一些GET參數。這些GET參數作為特殊令牌出現在規則的模式中,如下所示:🎜rrreee🎜🎜ParamName🎜表示GET參數名字,可選項🎜ParamPattern🎜表示將用於匹配GET參數值的正規表示式。當產生一個網址(URL)時,這些參數令牌將會被對應的參數值取代;當解析一個網址時,對應的GET參數將會透過解析結果來產生。 🎜🎜我們使用一些範例來解釋網址工作規則。我們假設我們的規則包含以下三個:🎜🎜🎜🎜🎜🎜rrreee🎜🎜🎜🎜🎜調用🎜$this->createUrl('post/list')🎜生成🎜/php。第一個規則適用。 🎜🎜🎜🎜呼叫🎜$this->createUrl('post/read',array('id'=>100))🎜產生🎜/index.php/post/100🎜。第二個規則適用。 🎜
    • 调用$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',
    )
    登入後複製
    登入後複製

    在上面的示例中, 我们在路由规则中使用了两个命名参数: _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 http://www.php.cn/ 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',
    )
    登入後複製
    登入後複製

    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 http://www.php.cn/, 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
    登入後複製
    登入後複製

    然后,我们设定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>',
    ),
    登入後複製
    登入後複製

    从以上可以看到,我们自定义了一个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
        }
    }
    登入後複製
    登入後複製

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

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

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

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

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


    來源:php.cn
    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
    熱門教學
    更多>
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!