Yii笔记---redirect重定向

Yii的redirect方法在CControler与CHttpRequest之中都有被定义,CController中的redirect调用了CHttpRequest中的redirect方法。咱们日常调用的是CControoler中的redirect方法php

 

framewok/web/CController中的定义web

1 public function redirect($url,$terminate=true,$statusCode=302)
2 {
3     if(is_array($url))
4     {
5         $route=isset($url[0]) ? $url[0] : '';
6         $url=$this->createUrl($route,array_splice($url,1));
7     }
8     Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
9 }

 

参数说明:数组

  @url:指定浏览器跳转到的url连接,若是$url为数组,则数组的第一个元素是由控制器/方法【controller/action】组成,其他的部分被视为GET参数,name-value对并调用了createUrl方法生成url。若是是字符串 直接调用的framework/web/CHttpRequest.php中的redirect方法。浏览器

  @terminate:调用redirect以后是否终止当前的应用。app

  @statusCode:表示HTTP的状态码,默认是302重定向函数

 

关于array_splice函数:把数组中的一部分去掉并用其它值取代,上面的array_splice($url,1)表示的是将$url数组的第一个元素去掉,获取到GET参数的值post

array array_splice  ( array &$input  , int $offset  [, int $length  = 0  [, mixed  $replacement  ]] )

 

 

关于createUrl函数:这个函数和redirect同样在多处有定义,分别在CController.php和CurlManager.php之中。最终的定义在CurlManager.php之中。this

下面是CController中的createURL的定义:url

 1     public function createUrl($route,$params=array(),$ampersand='&')
 2     {
 3         if($route==='')
 4             $route=$this->getId().'/'.$this->getAction()->getId();
 5         elseif(strpos($route,'/')===false)
 6             $route=$this->getId().'/'.$route;
 7         if($route[0]!=='/' && ($module=$this->getModule())!==null)
 8             $route=$module->getId().'/'.$route;
 9         return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
10     }

 

从这里能够看出来几种状况:spa

  一、若是redirect没有带参数则$route为空的状况,会被定向到 当前控制器的当前方法 $route=$this->getId().'/'.$this->getAction()->getId();

  二、若是$route中不带‘/’,例如 $this->render('index',array('post'=>$questions));只接了方法而没有控制器,程序会自动获取到当前的控制器方法ID

  三、route中有‘/’字符,可是不在首位置,而且查找当前控制器是否位于模块之中;例如 $this->redirect(array('step/show','id'=>1));  这种状况程序会自动判断是不是模块,咱们在调用createUrl的时候就能够不用跟上模块的名称,若是在模块中调用主控制器中的方法时 咱们能够在首字母处加上'/'字符。而且程序在最后都会去掉$route先后的/字符。

 

framework/web/CHttpRequest.php中的定义

1 public function redirect($url,$terminate=true,$statusCode=302)
2     {
3         if(strpos($url,'/')===0 && strpos($url,'//')!==0)
4             $url=$this->getHostInfo().$url;
5         header('Location: '.$url, true, $statusCode);
6         if($terminate)
7             Yii::app()->end();
8     }

 

若是CController之中的redirect的$url参数不是数组,则会直接调用该函数,若是$url不是以'/'开头则会直接跳转,这种状况致使在模块中重定向失败,因此建议在调用CController.php之中redirect方法时都是用数组做为参数进行传递

从这能够看出redirect方法最终仍是调用的php原生态的header函数

Yii::app()->end(); 直接调用的是php的exit()函数。

相关文章
相关标签/搜索