yii框架中的Url生產(chǎn)問題小結(jié)
更新時間:2012年01月16日 22:32:27 作者:
yii框架中的Url生產(chǎn)問題小結(jié),需要的朋友可以參考下。
復(fù)制代碼 代碼如下:
<?php echo CHtml::link('錯誤鏈接','user/register')?>
<?php echo CHtml::link('正確鏈接',array('user/register'))?>
假定設(shè)定了UrlManager的配置為Path模式,用yii默認(rèn)的配置:
復(fù)制代碼 代碼如下:
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
上面兩行代碼會生產(chǎn)什么樣的鏈接地址?
http://<site-addr>/user/register //錯誤鏈接
http://<site-addr>/index.php/user/register //正確鏈接
第一個鏈接是錯誤的,瀏覽器會返回404錯誤。第二個鏈接會訪問UserController的Register方法。區(qū)別就在于第二個鏈接在生成的時候我們傳入的參數(shù)是一個array數(shù)組,而第一個方法是一個簡單字符串。Yii在處理Url的時候,遇到簡單字符串會直接使用該字符串作為最終的Url,而當(dāng)遇到數(shù)組的時候會調(diào)用Controller的CreateUrl來生成Url.
說到簡單字符串,這兩個鏈接中其實(shí)有一個非常本質(zhì)的區(qū)別。雖然同樣都是字符串'user/register',但是在第一個字符串中就代表一個13個字符的相對路徑,而第二個鏈接中則代表UserController的registerAction,是有著特俗意義的。
附上Yii處理Url的方法NormalizeUrl的源代碼:
復(fù)制代碼 代碼如下:
/**
* Normalizes the input parameter to be a valid URL.
*
* If the input parameter is an empty string, the currently requested URL will be returned.
*
* If the input parameter is a non-empty string, it is treated as a valid URL and will
* be returned without any change.
*
* If the input parameter is an array, it is treated as a controller route and a list of
* GET parameters, and the {@link CController::createUrl} method will be invoked to
* create a URL. In this case, the first array element refers to the controller route,
* and the rest key-value pairs refer to the additional GET parameters for the URL.
* For example, <code>array('post/list', 'page'=>3)</code> may be used to generate the URL
* <code>/index.php?r=post/list&page=3</code>.
*
* @param mixed $url the parameter to be used to generate a valid URL
* @return string the normalized URL
*/
public static function normalizeUrl($url)
{
if(is_array($url))
{
if(isset($url[0]))
{
if(($c=Yii::app()->getController())!==null)
$url=$c->createUrl($url[0],array_splice($url,1));
else
$url=Yii::app()->createUrl($url[0],array_splice($url,1));
}
else
$url='';
}
return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
}
相關(guān)文章
給apache2.2加上mod_encoding模塊後 php5.2.0 處理url出現(xiàn)bug
給apache2.2加上mod_encoding模塊後 php5.2.0 處理url出現(xiàn)bug...2007-04-04
php中使用addslashes函數(shù)報錯問題的解決方法
php中使用addslashes函數(shù)報錯問題的解決方法,需要的朋友可以參考下2013-02-02
淺談ThinkPHP中initialize和construct的區(qū)別
下面小編就為大家?guī)硪黄獪\談ThinkPHP中initialize和construct的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04
php str_getcsv把字符串解析為數(shù)組的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄猵hp str_getcsv把字符串解析為數(shù)組的實(shí)現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04

