yii框架中的Url生产问题小结

yipeiwu_com6年前PHP代码库
复制代码 代码如下:

<?php echo CHtml::link('错误链接','user/register')?>
<?php echo CHtml::link('正确链接',array('user/register'))?>

假定设定了UrlManager的配置为Path模式,用yii默认的配置:
复制代码 代码如下:

'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>',
),
),

上面两行代码会生产什么样的链接地址?
http://<site-addr>/user/register //错误链接
http://<site-addr>/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('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;
}

相关文章

PHP 文件上传全攻略

1.表单部分 允许用户上传文件,在HTML表单的声明中要加上一个上传的属性: enctype = 'multipart/form-data' 表单的method必须是POST 表单选项M...

php session劫持和防范的方法

session 数据暴露会话数据常会包含一些个人信息和其它敏感数据。基于这个原因,会话数据的暴露是被普遍关心的问题。一般来说,暴露的范围不会很大,因为会话数据是保存在服务器环境中的,而不...

PHP在同一域名下两个不同的项目做独立登录机制详解

PHP在同一域名下两个不同的项目做独立登录机制详解

前言 目前有这样一个需求,在一个域名下 如:http://example.com 下,有两个项目,example.com/a/,example.com/b/,这两个项目是相互独立的程序,...

PHP 在5.1.* 和5.2.*之间 PDO数据库操作中的不同之处小结

介绍 今天发现php5.1.*和php5.2.*在数据库预编译代码执行的时候出现差异。 预编译优点 1.使用占位符,避免逐字输入数据到SQL中。自动处理引号和反斜线等字符的转义——增加安...

Yii2使用驼峰命名的形式访问控制器(实例讲解)

Yii2使用驼峰命名的形式访问控制器(实例讲解)

yii2在使用的时候,访问控制器的时候,如果控制器的名称是驼峰命名法,那访问的url中要改成横线的形式。例如: public function actionRoomUpdate()...