YII Framework学习教程-YII的forward\redirect-2011-11-18

以下代码都是在SiteController中

/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()

进行的。


1.YII的redirect


 

参数

($url,$terminate=true,$statusCode=302)

$url----url地址 

$terminate是否终止后续程序的执行

$statusCode状态码




使用方法

$this->redirect(array('index'));

对应的是当前controller的index action

http://www.localyii.com/testwebap/index.php?r=user/index

$this->redirect(array('view','id'=>$model->id));

对应的是当前controller的view action并传递id参数值为3

http://www.localyii.com/testwebap/index.php?r=user/view&id=3


$this->redirect(array('/site/contact','id'=>12));

$this->redirect(array('site/contact','id'=>12));


http://www.localyii.com/testwebap/index.php?r=site/contact&id=12


$this->redirect(array('site/contact','id'=>'idv','name'=>'namev'));

http://www.localyii.com/testwebap/index.php?r=site/contact&id=idv&name=namev

$this->redirect(array('site/contact','v1','v2','v3'));

http://www.localyii.com/testwebap/index.php?r=site/contact&0=v1&1=v2&2=v3


$this->redirect(array('site/contact','v1','v2','v3','#'=>'ttt'));

带anchor的

http://www.localyii.com/testwebap/index.php?r=site/contact&0=v1&1=v2&2=v3#ttt


$this->redirect(array('user/create','v1','v2','v3','#'=>'ttt'));

http://www.localyii.com/testwebap/index.php?r=user/create&0=v1&1=v2&2=v3#ttt


modules的redirect

$this->redirect(array('testmod/default/index','v1','v2','v3','#'=>'ttt'));

http://www.localyii.com/testwebap/index.php?r=testmod/default/index&0=v1&1=v2&2=v3#ttt


跳转到一个绝对路径

$this->redirect('http://www.baidu.com');



实现思路

class CController extends CBaseController

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


如果url是数组时,数组的第一个值会当作route。其他的当作参数。

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

array_splice — 把数组中的一部分去掉并用其它值取代



<?php
$input 
= array("red""green""blue""yellow");
array_splice($input2);
// $input is now array("red", "green")

$input = array("red""green""blue""yellow");
array_splice($input1, -1);
// $input is now array("red", "yellow")

$input = array("red""green""blue""yellow");
array_splice($input1count($input), "orange");
// $input is now array("red", "orange")

$input = array("red""green""blue""yellow");
array_splice($input, -11, array("black""maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red""green""blue""yellow");
array_splice($input30"purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

class CHttpRequest extends CApplicationComponent

 

public function redirect($url,$terminate=true,$statusCode=302)
	{
		if(strpos($url,'/')===0)
			$url=$this->getHostInfo().$url;
		header('Location: '.$url, true, $statusCode);
		if($terminate)
			Yii::app()->end();
	}

	public function createUrl($route,$params=array(),$ampersand='&')
	{
		unset($params[$this->routeVar]);
		foreach($params as &$param)
			if($param===null)
				$param='';
		if(isset($params['#']))
		{
			$anchor='#'.$params['#'];
			unset($params['#']);
		}
		else
			$anchor='';
		$route=trim($route,'/');
		foreach($this->_rules as $i=>$rule)
		{
			if(is_array($rule))
				$this->_rules[$i]=$rule=Yii::createComponent($rule);
			if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
			{
				if($rule->hasHostInfo)
					return $url==='' ? '/'.$anchor : $url.$anchor;
				else
					return $this->getBaseUrl().'/'.$url.$anchor;
			}
		}
		return $this->createUrlDefault($route,$params,$ampersand).$anchor;
	}
	protected function createUrlDefault($route,$params,$ampersand)
	{
		if($this->getUrlFormat()===self::PATH_FORMAT)
		{
			$url=rtrim($this->getBaseUrl().'/'.$route,'/');
			if($this->appendParams)
			{
				$url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
				return $route==='' ? $url : $url.$this->urlSuffix;
			}
			else
			{
				if($route!=='')
					$url.=$this->urlSuffix;
				$query=$this->createPathInfo($params,'=',$ampersand);
				return $query==='' ? $url : $url.'?'.$query;
			}
		}
		else
		{
			$url=$this->getBaseUrl();
			if(!$this->showScriptName)
				$url.='/';
			if($route!=='')
			{
				$url.='?'.$this->routeVar.'='.$route;
				if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
					$url.=$ampersand.$query;
			}
			else if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
				$url.='?'.$query;
			return $url;
		}
	}



2.YII的forward

使用方法

参数

$route

是string。一个url路径

$exit

 $this->forward('/testmod/default/index');

$this->forward('testmod/default/index'); 

地址栏url 

 http://www.localyii.com/testwebap/index.php

$this->forward('testmod/default/index'); 

实现思路

class CController extends CBaseController

 

/**
	 * Processes the request using another controller action.
	 * This is like {@link redirect}, but the user browser's URL remains unchanged.
	 * In most cases, you should call {@link redirect} instead of this method.
	 * @param string $route the route of the new controller action. This can be an action ID, or a complete route
	 * with module ID (optional in the current module), controller ID and action ID. If the former, the action is assumed
	 * to be located within the current controller.
	 * @param boolean $exit whether to end the application after this call. Defaults to true.
	 * @since 1.1.0
	 */

public function forward($route,$exit=true)
	{
		if(strpos($route,'/')===false)
			$this->run($route);
		else
		{
			if($route[0]!=='/' && ($module=$this->getModule())!==null)
				$route=$module->getId().'/'.$route;
			Yii::app()->runController($route);
		}
		if($exit)
			Yii::app()->end();
	}

public function runController($route)
	{
		if(($ca=$this->createController($route))!==null)
		{
			list($controller,$actionID)=$ca;
			$oldController=$this->_controller;
			$this->_controller=$controller;
			$controller->init();
			$controller->run($actionID);
			$this->_controller=$oldController;
		}
		else
			throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
				array('{route}'=>$route===''?$this->defaultController:$route)));
	}
	public function createController($route,$owner=null)
	{
		if($owner===null)
			$owner=$this;
		if(($route=trim($route,'/'))==='')
			$route=$owner->defaultController;
		$caseSensitive=$this->getUrlManager()->caseSensitive;
		$route.='/';
		while(($pos=strpos($route,'/'))!==false)
		{
			$id=substr($route,0,$pos);
			if(!preg_match('/^\w+$/',$id))
				return null;
			if(!$caseSensitive)
				$id=strtolower($id);
			$route=(string)substr($route,$pos+1);
			if(!isset($basePath))  // first segment
			{
				if(isset($owner->controllerMap[$id]))
				{
					return array(
						Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
						$this->parseActionParams($route),
					);
				}
				if(($module=$owner->getModule($id))!==null)
					return $this->createController($route,$module);
				$basePath=$owner->getControllerPath();
				$controllerID='';
			}
			else
				$controllerID.='/';
			$className=ucfirst($id).'Controller';
			$classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
			if(is_file($classFile))
			{
				if(!class_exists($className,false))
					require($classFile);
				if(class_exists($className,false) && is_subclass_of($className,'CController'))
				{
					$id[0]=strtolower($id[0]);
					return array(
						new $className($controllerID.$id,$owner===$this?null:$owner),
						$this->parseActionParams($route),
					);
				}
				return null;
			}
			$controllerID.=$id;
			$basePath.=DIRECTORY_SEPARATOR.$id;
		}
	}




forward和redirect的区别显而易见

浏览器url地址

是否支持绝对地址

是否传递参数












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值