Yii框架 $this->redirect与$this->createUrl 的路由设置

  •   
  • 11308
  • PHP
  • 7
  • super_dodo
  • 2014/11/19

在Yii框架中常常用到 $this->redirect与$this->createUrl这两个函数。现在对其大概的区分一下,不吝赐教。

1、$this->redirect中的$this指的是当前的controller(可能是应用程序/protected/controllers/下的controller,也可能是/protected/module/controllers下的controller)

2、跳转情况分析

(1)、$this->redirect('index');    
跳转至当前controller中名为index的action,如果当前没有controller,
则跳转至/protected/config/mani.php中defaultController参数指定的controller的index(action方法);

(2)、$this->redirect('/index');    
跳转至/protected/controllers/中index这个controller默认的action;
原因分析:redirect参数中,如果以/开始的参数,则跳转至根目录下,否则跳转至当前所属的controller

(3)、redirect参数可以随便设置,无论是几层都OK的,例如
$this->redirect('post/index');
$this->redirect('/login/login');
$this->redirect('test/post/delete');

3、特殊情况分析
如果/protected/config/main.php中开启了urlManager,则按以下方法进行跳转:

例如,urlManager中添加了规则
'rules' => array(
     'index'        => 'post/index',
     'login'        => 'login/login',
     'editTest'          => 'edit/article'
),

那么
(1)、$this->redirect('/index');则会跳转至http://localhost/post/index
(2)、而$this->redirect('index');不变还是按照情况2跳转;
(3)、$this->redirect(array('/edit/article', 'id'=>476));则会跳转至http://localhost/editTest/id/476,
如果使用$this->redirect(array('editTest', 'id'=>476));则会提示解析不了请求或者是跳转至http://localhost/editTest/id/476(如果存在editTest这个controller);

PS:如果有多个参数,则如下调用$this->redirect(array('toUrl/action', 'one'=> '1', 'two' => '2', .........));

4、createUrl会根据真实地址,组织成路由格式的地址,使用方法如下:

(1)、$this->createUrl('post/index');
如果是创建类似http://localhost/post/index这样的地址,可以使用$this->createUrl('/post/index');多加一个符号:/
        
PS:Yii::app()->createUrl,它是依赖于具体的路由的。

 (2)、$this->createUrl('edit/article', array('id'=>476, 'cid' => 54));
createUrl传入参数形式

温馨提示:redirect和createUrl在参数传入存在区别,前者是直接key=>value形式添加多个参数的,后者则是将所有参数放在一个数组中传入,注意!!!

人生最痛苦的是梦醒了无路可走。做梦的人是幸福的;倘没有看出可以走的路,最要紧的是不要去惊醒他。