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:參數值正則(可選)| 呼叫 | 生成 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)。
'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'] 取得。
規則過多會降低解析效能(逐一嘗試匹配)。高流量網站應精簡規則、優先頻用規則前置、考慮快取解析結果。
Apache .htaccess:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
配合 'showScriptName'=>false 即可得到乾淨 URL。