本文实例讲述了zend framework动作助手redirector用法。分享给大家供大家参考,具体如下:
redirector 提供另一种实现方式,帮助程序重定向到内部或者外部页面;
转向器(redirector)助手让你使用一个转向器对象帮助程序重定向到新的url。与_redirect()方法相比,它具有多项优势。例如能够在转向器对象中预先配置整个站点的行为,或者使用与zend_controller_action::_forward()相似的gotosimple($action, $controller, $module, $params)接口。
转向器拥有影响重定向行为的大量方法:
setcode() 设置重定向过程中使用的http响应码。
setexit() 在重定向后强制执行exit()方法。默认已设定。
setgotosimple()设置默认的url,当没有提供参数给gotosimple()方法时转向该url。可以使用类似zend_controller_action::_forward()的api:setgotosimple($action, $controller = null, $module = null, array $params = array());
setgotoroute()设置基于一个注册路由器的url。通过传入一个键/值数组和一个路由器名,它将根据路由器的类型和定义来组织url。
setgotourl()设置默认的url,当没有参数传入gotourl(),将使用该url。接受单个url字符串。
setprependbase()在setgotourl()、gotourl()或者gotourlandexit()指定的url前面,加入请求对象的基地址(base url)。
setuseabsoluteuri()强制转向器在重定向时使用绝对的uri。当该选项设定后,将使用$_server['http_host']、 $_server['server_port']和 $_server['https']以及重定向方法指定的url,来形成一个完整的uri。该选项目前默认关闭,将来的版本可能会默认开启。
此外,转向器中还有大量方法来执行实际的重定向。
gotosimple()使用setgotosimple()(类似_forward()的api)来构建url并执行重定向。
gotoroute()使用setgotoroute()(路由组装route-assembly)来构建url并执行重定向。
gotourl()使用setgotourl() url字符串)来构造url并执行重定向。
最后,你可以在任何时刻使用getredirecturl()确定当前的重定向url。
基础用例
example #5 设定选项
这个例子改变了几个选项,包括设定重定向时使用的http状态码为303,重定向时不默认退出,以及定义了默认的url供重定向使用。
class somecontroller extends zend_controller_action
{
/**
* redirector - defined for code completion
*
* @var zend_controller_action_helper_redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->gethelper('redirector');
// set the default options for the redirector
// since the object is registered in the helper broker, these
// become relevant for all actions from this point forward
$this->_redirector->setcode(303)
->setexit(false)
->setgotosimple("this-action",
"some-controller");
}
public function myaction()
{
/* do some stuff */
// redirect to a previously registered url, and force an exit
// to occur when done:
$this->_redirector->redirectandexit();
return; // never reached
}
}
example #6 使用默认设定
这个例子假定使用默认设定,也就意味着任何重定向将导致立即退出。
// alternative example
class alternativecontroller extends zend_controller_action
{
/**
* redirector - defined for code completion
*
* @var zend_controller_action_helper_redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->gethelper('redirector');
}
public function myaction()
{
/* do some stuff */
$this->_redirector
->gotourl('/my-controller/my-action/param1/test/param2/test2');
return; // never reached since default is to goto and exit
}
}
example #7 使用goto()的_forward()api
gotosimple()'s api 模拟了zend_controller_action::_forward()。主要的不同在于它通过传入的参数构造url,使用默认路由器的默认格式:module/:controller/:action/*。然后重定向而不是继续动作链循环。
class forwardcontroller extends zend_controller_action
{
/**
* redirector - defined for code completion
*
* @var zend_controller_action_helper_redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->gethelper('redirector');
}
public function myaction()
{
/* do some stuff */
// redirect to 'my-action' of 'my-controller' in the current
// module, using the params param1 => test and param2 => test2
$this->_redirector->gotosimple('my-action',
'my-controller',
null,
array('param1' => 'test',
'param2' => 'test2'
)
);
}
}
example #8 通过gotoroute()使用路由组装(route assembly)
下面的例子使用了路由器的assemble()方法,基于传入参数的关联数组来创建url。假定下面的路由已经注册:
$route = new zend_controller_router_route(
'blog/:year/:month/:day/:id',
array('controller' => 'archive',
'module' => 'blog',
'action' => 'view')
);
$router->addroute('blogarchive', $route);
给定一个数组,其中年份为2006,月份为4,日期为24,id为42,据此可以组装url/blog/2006/4/24/42。
class blogadmincontroller extends zend_controller_action
{
/**
* redirector - defined for code completion
*
* @var zend_controller_action_helper_redirector
*/
protected $_redirector = null;
public function init()
{
$this->_redirector = $this->_helper->gethelper('redirector');
}
public function returnaction()
{
/* do some stuff */
// redirect to blog archive. builds the following url:
// /blog/2006/4/24/42
$this->_redirector->gotoroute(
array('year' => 2006,
'month' => 4,
'day' => 24,
'id' => 42),
'blogarchive'
);
}
}
zend_controller_action_helper_redirector的源码。
通过源代码不难看出实现方法,以及常见的使用方法。
<?php
/**
* @see zend_controller_action_helper_abstract
*/
require_once 'zend/controller/action/helper/abstract.php';
/**
* @category zend
* @package zend_controller
* @subpackage zend_controller_action_helper
* @copyright copyright (c) 2005-2011 zend technologies usa inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd new bsd license
*/
class zend_controller_action_helper_redirector extends zend_controller_action_helper_abstract
{
/**
* http status code for redirects
* @var int
*/
protected $_code = 302;
/**
* whether or not calls to _redirect() should exit script execution
* @var boolean
*/
protected $_exit = true;
/**
* whether or not _redirect() should attempt to prepend the base url to the
* passed url (if it's a relative url)
* @var boolean
*/
protected $_prependbase = true;
/**
* url to which to redirect
* @var string
*/
protected $_redirecturl = null;
/**
* whether or not to use an absolute uri when redirecting
* @var boolean
*/
protected $_useabsoluteuri = false;
/**
* whether or not to close the session before exiting
* @var boolean
*/
protected $_closesessiononexit = true;
/**
* retrieve http status code to emit on {@link _redirect()} call
*
* @return int
*/
public function getcode()
{
return $this->_code;
}
/**
* validate http status redirect code
*
* @param int $code
* @throws zend_controller_action_exception on invalid http status code
* @return true
*/
protected function _checkcode($code)
{
$code = (int)$code;
if ((300 > $code) || (307 < $code) || (304 == $code) || (306 == $code)) {
require_once 'zend/controller/action/exception.php';
throw new zend_controller_action_exception('invalid redirect http status code (' . $code . ')');
}
return true;
}
/**
* retrieve http status code for {@link _redirect()} behaviour
*
* @param int $code
* @return zend_controller_action_helper_redirector provides a fluent interface
*/
public function setcode($code)
{
$this->_checkcode($code);
$this->_code = $code;
return $this;
}
/**
* retrieve flag for whether or not {@link _redirect()} will exit when finished.
*
* @return boolean
*/
public function getexit()
{
return $this->_exit;
}
/**
* retrieve exit flag for {@link _redirect()} behaviour
*
* @param boolean $flag
* @return zend_controller_action_helper_redirector provides a fluent interface
*/
public function setexit($flag)
{
$this->_exit = ($flag) ? true : false;
return $this;
}
/**
* retrieve flag for whether or not {@link _redirect()} will prepend the
* base url on relative urls
*
* @return boolean
*/
public function getprependbase()
{
return $this->_prependbase;
}
/**
* retrieve 'prepend base' flag for {@link _redirect()} behaviour
*
* @param boolean $flag
* @return zend_controller_action_helper_redirector provides a fluent interface
*/
public function setprependbase($flag)
{
$this->_prependbase = ($flag) ? true : false;
return $this;
}
/**
* retrieve flag for whether or not {@link redirectandexit()} shall close the session before
* exiting.
*
* @return boolean
*/
public function getclosesessiononexit()
{
return $this->_closesessiononexit;
}
/**
* set flag for whether or not {@link redirectandexit()} shall close the session before exiting.
*
* @param boolean $flag
* @return zend_controller_action_helper_redirector provides a fluent interface
*/
public function setclosesessiononexit($flag)
{
$this->_closesessiononexit = ($flag) ? true : false;
return $this;
}
/**
* return use absolute uri flag
*
* @return boolean
*/
public function getuseabsoluteuri()
{
return $this->_useabsoluteuri;
}
/**
* set use absolute uri flag
*
* @param boolean $flag
* @return zend_controller_action_helper_redirector provides a fluent interface
*/
public function setuseabsoluteuri($flag = true)
{
$this->_useabsoluteuri = ($flag) ? true : false;
return $this;
}
/**
* set redirect in response object
*
* @return void
*/
protected function _redirect($url)
{
if ($this->getuseabsoluteuri() && !preg_match('#^(https?|ftp)://#', $url)) {
$host = (isset($_server['http_host'])?$_server['http_host']:'');
$proto = (isset($_server['https'])&&$_server['https']!=="off") ? 'https' : 'http';
$port = (isset($_server['server_port'])?$_server['server_port']:80);
$uri = $proto . '://' . $host;
if ((('http' == $proto) && (80 != $port)) || (('https' == $proto) && (443 != $port))) {
// do not append if http_host already contains port
if (strrchr($host, ':') === false) {
$uri .= ':' . $port;
}
}
$url = $uri . '/' . ltrim($url, '/');
}
$this->_redirecturl = $url;
$this->getresponse()->setredirect($url, $this->getcode());
}
/**
* retrieve currently set url for redirect
*
* @return string
*/
public function getredirecturl()
{
return $this->_redirecturl;
}
/**
* determine if the baseurl should be prepended, and prepend if necessary
*
* @param string $url
* @return string
*/
protected function _prependbase($url)
{
if ($this->getprependbase()) {
$request = $this->getrequest();
if ($request instanceof zend_controller_request_http) {
$base = rtrim($request->getbaseurl(), '/');
if (!empty($base) && ('/' != $base)) {
$url = $base . '/' . ltrim($url, '/');
} else {
$url = '/' . ltrim($url, '/');
}
}
}
return $url;
}
/**
* set a redirect url of the form /module/controller/action/params
*
* @param string $action
* @param string $controller
* @param string $module
* @param array $params
* @return void
*/
public function setgotosimple($action, $controller = null, $module = null, array $params = array())
{
$dispatcher = $this->getfrontcontroller()->getdispatcher();
$request = $this->getrequest();
$curmodule = $request->getmodulename();
$usedefaultcontroller = false;
if (null === $controller && null !== $module) {
$usedefaultcontroller = true;
}
if (null === $module) {
$module = $curmodule;
}
if ($module == $dispatcher->getdefaultmodule()) {
$module = '';
}
if (null === $controller && !$usedefaultcontroller) {
$controller = $request->getcontrollername();
if (empty($controller)) {
$controller = $dispatcher->getdefaultcontrollername();
}
}
$params[$request->getmodulekey()] = $module;
$params[$request->getcontrollerkey()] = $controller;
$params[$request->getactionkey()] = $action;
$router = $this->getfrontcontroller()->getrouter();
$url = $router->assemble($params, 'default', true);
$this->_redirect($url);
}
/**
* build a url based on a route
*
* @param array $urloptions
* @param string $name route name
* @param boolean $reset
* @param boolean $encode
* @return void
*/
public function setgotoroute(array $urloptions = array(), $name = null, $reset = false, $encode = true)
{
$router = $this->getfrontcontroller()->getrouter();
$url = $router->assemble($urloptions, $name, $reset, $encode);
$this->_redirect($url);
}
/**
* set a redirect url string
*
* by default, emits a 302 http status header, prepends base url as defined
* in request object if url is relative, and halts script execution by
* calling exit().
*
* $options is an optional associative array that can be used to control
* redirect behaviour. the available option keys are:
* - exit: boolean flag indicating whether or not to halt script execution when done
* - prependbase: boolean flag indicating whether or not to prepend the base url when a relative url is provided
* - code: integer http status code to use with redirect. should be between 300 and 307.
*
* _redirect() sets the location header in the response object. if you set
* the exit flag to false, you can override this header later in code
* execution.
*
* if the exit flag is true (true by default), _redirect() will write and
* close the current session, if any.
*
* @param string $url
* @param array $options
* @return void
*/
public function setgotourl($url, array $options = array())
{
// prevent header injections
$url = str_replace(array("n", "r"), '', $url);
if (null !== $options) {
if (isset($options['exit'])) {
$this->setexit(($options['exit']) ? true : false);
}
if (isset($options['prependbase'])) {
$this->setprependbase(($options['prependbase']) ? true : false);
}
if (isset($options['code'])) {
$this->setcode($options['code']);
}
}
// if relative url, decide if we should prepend base url
if (!preg_match('|^[a-z]+://|', $url)) {
$url = $this->_prependbase($url);
}
$this->_redirect($url);
}
/**
* perform a redirect to an action/controller/module with params
*
* @param string $action
* @param string $controller
* @param string $module
* @param array $params
* @return void
*/
public function gotosimple($action, $controller = null, $module = null, array $params = array())
{
$this->setgotosimple($action, $controller, $module, $params);
if ($this->getexit()) {
$this->redirectandexit();
}
}
/**
* perform a redirect to an action/controller/module with params, forcing an immdiate exit
*
* @param mixed $action
* @param mixed $controller
* @param mixed $module
* @param array $params
* @return void
*/
public function gotosimpleandexit($action, $controller = null, $module = null, array $params = array())
{
$this->setgotosimple($action, $controller, $module, $params);
$this->redirectandexit();
}
/**
* redirect to a route-based url
*
* uses route's assemble method tobuild the url; route is specified by $name;
* default route is used if none provided.
*
* @param array $urloptions array of key/value pairs used to assemble url
* @param string $name
* @param boolean $reset
* @param boolean $encode
* @return void
*/
public function gotoroute(array $urloptions = array(), $name = null, $reset = false, $encode = true)
{
$this->setgotoroute($urloptions, $name, $reset, $encode);
if ($this->getexit()) {
$this->redirectandexit();
}
}
/**
* redirect to a route-based url, and immediately exit
*
* uses route's assemble method tobuild the url; route is specified by $name;
* default route is used if none provided.
*
* @param array $urloptions array of key/value pairs used to assemble url
* @param string $name
* @param boolean $reset
* @return void
*/
public function gotorouteandexit(array $urloptions = array(), $name = null, $reset = false)
{
$this->setgotoroute($urloptions, $name, $reset);
$this->redirectandexit();
}
/**
* perform a redirect to a url
*
* @param string $url
* @param array $options
* @return void
*/
public function gotourl($url, array $options = array())
{
$this->setgotourl($url, $options);
if ($this->getexit()) {
$this->redirectandexit();
}
}
/**
* set a url string for a redirect, perform redirect, and immediately exit
*
* @param string $url
* @param array $options
* @return void
*/
public function gotourlandexit($url, array $options = array())
{
$this->setgotourl($url, $options);
$this->redirectandexit();
}
/**
* exit(): perform exit for redirector
*
* @return void
*/
public function redirectandexit()
{
if ($this->getclosesessiononexit()) {
// close session, if started
if (class_exists('zend_session', false) && zend_session::isstarted()) {
zend_session::writeclose();
} elseif (isset($_session)) {
session_write_close();
}
}
$this->getresponse()->sendheaders();
exit();
}
/**
* direct(): perform helper when called as
* $this->_helper->redirector($action, $controller, $module, $params)
*
* @param string $action
* @param string $controller
* @param string $module
* @param array $params
* @return void
*/
public function direct($action, $controller = null, $module = null, array $params = array())
{
$this->gotosimple($action, $controller, $module, $params);
}
/**
* overloading
*
* overloading for old 'goto', 'setgoto', and 'gotoandexit' methods
*
* @param string $method
* @param array $args
* @return mixed
* @throws zend_controller_action_exception for invalid methods
*/
public function __call($method, $args)
{
$method = strtolower($method);
if ('goto' == $method) {
return call_user_func_array(array($this, 'gotosimple'), $args);
}
if ('setgoto' == $method) {
return call_user_func_array(array($this, 'setgotosimple'), $args);
}
if ('gotoandexit' == $method) {
return call_user_func_array(array($this, 'gotosimpleandexit'), $args);
}
require_once 'zend/controller/action/exception.php';
throw new zend_controller_action_exception(sprintf('invalid method "%s" called on redirector', $method));
}
}
更多关于zend相关内容感兴趣的读者可查看本站专题:《zend framework框架入门教程》、《php优秀开发框架总结》、《yii框架入门及常用技巧总结》、《thinkphp入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:
本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!