對於yii框架中Url的生產問題的解決

不言
發布: 2023-04-01 13:40:02
原創
1250 人瀏覽過

yii框架中的Url生產問題小結,需要的朋友可以參考下。

程式碼如下:

<?php echo CHtml::link(&#39;错误链接&#39;,&#39;user/register&#39;)?> 
<?php echo CHtml::link(&#39;正确链接&#39;,array(&#39;user/register&#39;))?>
登入後複製

假定設定了UrlManager的配置為Path模式,用yii預設的配置: 

&#39;urlManager&#39;=>array( 
&#39;urlFormat&#39;=>&#39;path&#39;, 
&#39;rules&#39;=>array( 
&#39;<controller:\w+>/<id:\d+>&#39;=>&#39;<controller>/view&#39;, 
&#39;<controller:\w+>/<action:\w+>/<id:\d+>&#39;=>&#39;<controller>/<action>&#39;, 
&#39;<controller:\w+>/<action:\w+>&#39;=>&#39;<controller>/<action>&#39;, 
), 
),
登入後複製

上面兩行程式碼會生產什麼樣的鏈接地址?
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, <code>array(&#39;post/list&#39;, &#39;page&#39;=>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=&#39;&#39;; 
} 
return $url===&#39;&#39; ? Yii::app()->getRequest()->getUrl() : $url; 
}
登入後複製

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

關於yii分頁元件的用法

#關於yii使用bootstrap的分頁樣式

#對於Yii2.0表關聯查詢的分析

#

以上是對於yii框架中Url的生產問題的解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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