首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii Framework 教程 (5):CUrlManager 深度解析——打造美觀、SEO 友善的 URL

     編輯:PHP 綜合知識

URL 管理雙重職責

  1. 解析:將用戶請求的 URL 轉為內部路由與參數
  2. 建立:createUrl() 依規則生成可被解析的 URL

核心類別:CUrlManager,作為應用組件 urlManager 註冊。

配置範例

<?php
return array(
    'components' => array(
        'urlManager' => array(
            'urlFormat' => 'path', // path 格式:/controller/action/param/value
            'showScriptName' => false, // 隱藏 index.php(需配合 .htaccess)
            'rules' => array(
                'game/guess/<g:\w>' => 'game/guess',
                'post/<id:\d+>' => 'post/view',
                'post/<year:\d{4}>/<title>' => 'post/view',
                'posts' => 'post/index',
            ),
        ),
    ),
);

規則語法詳解

  • 模式:路徑資訊部分的正則表示式(無分隔符、修飾符)
  • 路由:ControllerID/ActionID 格式
  • 參數綁定:<ParamName:ParamPattern>
    • ParamName:GET 參數名
    • ParamPattern:參數值正則(可選)

createUrl() 生成範例

呼叫生成 URL匹配規則
createUrl('post/index')/posts'posts'=>'post/index'
createUrl('post/view', array('id'=>100))/post/100'post/<id:\d+>'=>'post/view'
createUrl('post/view', array('year'=>2008,'title'=>'a sample post'))/post/2008/a%20sample%20post'post/<year:\d{4}>/<title>'=>'post/view'
createUrl('post/view')/post/view無規則匹配,退回預設格式

額外參數處理

// 呼叫
createUrl('post/view', array('id'=>100, 'year'=>2008))
// 生成:/post/100?year=2008  (year 不在規則中,附加查詢字串)

// 若規則加尾碼
'post/<id:\d+>/*' => 'post/view'
// 生成:/post/100/year/2008

解析請求範例

請求 /post/100 → 規則 'post/<id:\d+>'=>'post/view' 匹配 → 路由 post/view、GET 參數 array('id'=>100)。

Hangman 實例中的應用

'game/guess/<g:\w>' => 'game/guess'

字母鏈接:CHtml::linkButton(chr($i), array('submit'=>array('guess','g'=>chr($i))))
產生 /game/guess/A 或 /game/guess/?g=A,控制器透過 $_GET['g'] 取得。

效能提醒

規則過多會降低解析效能(逐一嘗試匹配)。高流量網站應精簡規則、優先頻用規則前置、考慮快取解析結果。

隱藏 index.php

Apache .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

配合 'showScriptName'=>false 即可得到乾淨 URL。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved