yii架構中的Url生產問題小結_PHP教程

來源:互聯網
上載者:User
複製代碼 代碼如下:



假定設定了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的配置為...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.