找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 49|回复: 0
打印 上一主题 下一主题

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

[复制链接]

2617

主题

2617

帖子

7789

积分

论坛元老

Rank: 8Rank: 8

积分
7789
跳转到指定楼层
楼主
发表于 2018-2-14 08:31:39 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            [U]复制代码[/U] 代码如下:



假定设定了UrlManager的配置为Path模式,用yii默认的配置:
[U]复制代码[/U] 代码如下:
'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的源代码:
[U]复制代码[/U] 代码如下:
/**
* 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;
}
            
            
您可能感兴趣的文章:
  • yii上传文件或图片实例
  • Yii结合CKEditor实现图片上传功能
  • yii实现图片上传及缩略图生成的方法
  • Yii获取当前url和域名的方法
  • yii使用activeFileField控件实现上传文件与图片的方法
  • YII使用url组件美化管理的方法
  • yii2整合百度编辑器umeditor及umeditor图片上传问题的解决办法
  • Yii隐藏URL中index.php的方法
  • Yii2针对指定url的生成及图片等的引入方法小结
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端