複製代碼 代碼如下:
假定設定了UrlManager的配置為Path模式,用yii預設的配置:
複製代碼 代碼如下:
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'/'=>'/view',
'//'=>'/',
'/'=>'/',
),
),
上面兩行代碼會生產什麼樣的連結地址?
http:///user/register //錯誤連結
http:///index.php/user/register //正確連結
第一個連結是錯誤的,瀏覽器會返回404錯誤。第二個連結會訪問UserController的Register方法。區別就在於第二個連結在產生的時候我們傳入的參數是一個array數組,而第一個方法是一個簡單字串。Yii在處理Url的時候,遇到簡單字串會直接使用該字串作為最終的Url,而當遇到數組的時候會調用Controller的CreateUrl來產生Url.
說到簡單字串,這兩個連結中其實有一個非常本質的區別。雖然同樣都是字串'user/register',但是在第一個字串中就代表一個13個字元的相對路徑,而第二個連結中則代表UserController的registerAction,是有著特俗意義的。
附上Yii處理Url的方法NormalizeUrl的原始碼:
複製代碼 代碼如下:
/**
* 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,
array('post/list', 'page'=>3) may be used to generate the URL
*
/index.php?r=post/list&page=3.
*
* @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;
}
http://www.bkjia.com/PHPjc/324933.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/324933.htmlTechArticle複製代碼 代碼如下: ?php echo CHtml::link('錯誤連結','user/register')? ?php echo CHtml::link('正確連結',array('user/register'))? 假定設定了UrlManager的配置為...