Summary of Url production issues in the yii framework

  • 2020-05-12 02:17:43
  • OfStack

 
<?php echo CHtml::link(' Wrong link ','user/register')?> 
<?php echo CHtml::link(' The correct link ',array('user/register'))?> 

Suppose the configuration of UrlManager is set to Path mode, and the default configuration of yii is used:
 
'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>', 
), 
), 

What kind of links will the above two lines of code produce?
http:// < site-addr > /user/register // error link
http:// < site-addr > / index php user register / / link correctly
The first link is incorrect and the browser returns a 404 error. The second link accesses the Register method of UserController. The difference is that when the second link is generated we pass in an array array and the first method is a simple string. When dealing with Url, Yii will directly use the simple string as the final Url, and when encountering an array, Controller's CreateUrl will be called to generate Url.
When it comes to simple strings, there's actually a very fundamental difference between the two links. Although both are strings 'user/register', the first string represents the relative path of 1 13-character character, while the second link represents registerAction of UserController, which is of particular vulgar significance.
Attached is the source code for Yii's Url method 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('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; 
} 

Related articles: