Zend Framework動(dòng)作助手Redirector用法實(shí)例詳解
本文實(shí)例講述了Zend Framework動(dòng)作助手Redirector用法。分享給大家供大家參考,具體如下:
Redirector 提供另一種實(shí)現(xiàn)方式,幫助程序重定向到內(nèi)部或者外部頁(yè)面;
轉(zhuǎn)向器(Redirector)助手讓你使用一個(gè)轉(zhuǎn)向器對(duì)象幫助程序重定向到新的URL。與_redirect()方法相比,它具有多項(xiàng)優(yōu)勢(shì)。例如能夠在轉(zhuǎn)向器對(duì)象中預(yù)先配置整個(gè)站點(diǎn)的行為,或者使用與Zend_Controller_Action::_forward()相似的gotoSimple($action, $controller, $module, $params)接口。
轉(zhuǎn)向器擁有影響重定向行為的大量方法:
setCode() 設(shè)置重定向過(guò)程中使用的HTTP響應(yīng)碼。
setExit() 在重定向后強(qiáng)制執(zhí)行exit()方法。默認(rèn)已設(shè)定。
setGotoSimple()設(shè)置默認(rèn)的URL,當(dāng)沒(méi)有提供參數(shù)給gotoSimple()方法時(shí)轉(zhuǎn)向該URL??梢允褂妙愃芞end_Controller_Action::_forward()的API:setGotoSimple($action, $controller = null, $module = null, array $params = array());
setGotoRoute()設(shè)置基于一個(gè)注冊(cè)路由器的URL。通過(guò)傳入一個(gè)鍵/值數(shù)組和一個(gè)路由器名,它將根據(jù)路由器的類型和定義來(lái)組織URL。
setGotoUrl()設(shè)置默認(rèn)的URL,當(dāng)沒(méi)有參數(shù)傳入gotoUrl(),將使用該URL。接受單個(gè)URL字符串。
setPrependBase()在setGotoUrl()、gotoUrl()或者gotoUrlAndExit()指定的URL前面,加入請(qǐng)求對(duì)象的基地址(base URL)。
setUseAbsoluteUri()強(qiáng)制轉(zhuǎn)向器在重定向時(shí)使用絕對(duì)的URI。當(dāng)該選項(xiàng)設(shè)定后,將使用$_SERVER['HTTP_HOST']、 $_SERVER['SERVER_PORT']和 $_SERVER['HTTPS']以及重定向方法指定的URL,來(lái)形成一個(gè)完整的URI。該選項(xiàng)目前默認(rèn)關(guān)閉,將來(lái)的版本可能會(huì)默認(rèn)開(kāi)啟。
此外,轉(zhuǎn)向器中還有大量方法來(lái)執(zhí)行實(shí)際的重定向。
gotoSimple()使用setGotoSimple()(類似_forward()的API)來(lái)構(gòu)建URL并執(zhí)行重定向。
gotoRoute()使用setGotoRoute()(路由組裝route-assembly)來(lái)構(gòu)建URL并執(zhí)行重定向。
gotoUrl()使用setGotoUrl() URL字符串)來(lái)構(gòu)造URL并執(zhí)行重定向。
最后,你可以在任何時(shí)刻使用getRedirectUrl()確定當(dāng)前的重定向URL。
基礎(chǔ)用例
Example #5 設(shè)定選項(xiàng)
這個(gè)例子改變了幾個(gè)選項(xiàng),包括設(shè)定重定向時(shí)使用的HTTP狀態(tài)碼為303,重定向時(shí)不默認(rèn)退出,以及定義了默認(rèn)的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 使用默認(rèn)設(shè)定
這個(gè)例子假定使用默認(rèn)設(shè)定,也就意味著任何重定向?qū)?dǎo)致立即退出。
// 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()。主要的不同在于它通過(guò)傳入的參數(shù)構(gòu)造URL,使用默認(rèn)路由器的默認(rèn)格式:module/:controller/:action/*。然后重定向而不是繼續(xù)動(dòng)作鏈循環(huán)。
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 通過(guò)gotoRoute()使用路由組裝(route assembly)
下面的例子使用了路由器的assemble()方法,基于傳入?yún)?shù)的關(guān)聯(lián)數(shù)組來(lái)創(chuàng)建URL。假定下面的路由已經(jīng)注冊(cè):
$route = new Zend_Controller_Router_Route(
'blog/:year/:month/:day/:id',
array('controller' => 'archive',
'module' => 'blog',
'action' => 'view')
);
$router->addRoute('blogArchive', $route);
給定一個(gè)數(shù)組,其中年份為2006,月份為4,日期為24,id為42,據(jù)此可以組裝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的源碼。
通過(guò)源代碼不難看出實(shí)現(xiàn)方法,以及常見(jiàn)的使用方法。
<?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));
}
}
更多關(guān)于zend相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Zend FrameWork框架入門(mén)教程》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《Yii框架入門(mén)及常用技巧總結(jié)》、《ThinkPHP入門(mén)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
- Zend Framework教程之Zend_Helpers動(dòng)作助手ViewRenderer用法詳解
- Zend Framework教程之動(dòng)作的基類Zend_Controller_Action詳解
- Zend Framework動(dòng)作助手Url用法詳解
- Zend Framework動(dòng)作助手Json用法實(shí)例分析
- Zend Framework動(dòng)作助手FlashMessenger用法詳解
- Zend Framework創(chuàng)建自己的動(dòng)作助手詳解
- Zend Framework動(dòng)作助手(Zend_Controller_Action_Helper)用法詳解
- Zend Framework教程之前端控制器Zend_Controller_Front用法詳解
- php入門(mén)教程之Zend Studio設(shè)置與開(kāi)發(fā)實(shí)例
- Zend Framework開(kāi)發(fā)入門(mén)經(jīng)典教程
- Zend Framework動(dòng)作控制器用法示例
相關(guān)文章
php 使用curl模擬登錄人人(校內(nèi))網(wǎng)的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇php 使用curl模擬登錄人人(校內(nèi))網(wǎng)的簡(jiǎn)單實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06
關(guān)于擴(kuò)展 Laravel 默認(rèn) Session 中間件導(dǎo)致的 Session 寫(xiě)入失效問(wèn)題分析
這篇文章主要介紹了關(guān)于擴(kuò)展 Laravel 默認(rèn) Session 中間件導(dǎo)致的 Session 寫(xiě)入失效問(wèn)題分析的相關(guān)資料,需要的朋友可以參考下2016-01-01
thinkphp 中的volist標(biāo)簽在ajax操作中的特殊性(推薦)
在一個(gè)ThinkPHP的復(fù)雜頁(yè)面(包含volist)中實(shí)現(xiàn)volist標(biāo)簽顯示Jquery查詢結(jié)果的返回。這篇文章給大家介紹了thinkphp 中的volist標(biāo)簽在ajax操作中的特殊性(推薦),需要的朋友參考下吧2018-01-01
PHP實(shí)現(xiàn)字母數(shù)字混合驗(yàn)證碼功能
PHP實(shí)現(xiàn)字母數(shù)字混合驗(yàn)證碼,支持自定義驗(yàn)證碼、驗(yàn)證碼圖片、寬度、高度、個(gè)數(shù)、背景圖片,本文給大家分享實(shí)例代碼,感興趣的朋友跟隨小編一起看看吧2019-07-07
PHP CURL或file_get_contents獲取網(wǎng)頁(yè)標(biāo)題的代碼及兩者效率的穩(wěn)定性問(wèn)題
PHP CURL與file_get_contents函數(shù)都可以獲取遠(yuǎn)程服務(wù)器上的文件保存到本地,但在性能上面兩者完全不在同一個(gè)級(jí)別,下面通過(guò)一個(gè)例子給大家介紹PHP CURL或file_get_contents獲取網(wǎng)頁(yè)標(biāo)題的代碼及兩者效率的穩(wěn)定性問(wèn)題,需要的朋友參考下2015-11-11
Laravel實(shí)現(xiàn)登錄跳轉(zhuǎn)功能
網(wǎng)站管理員登錄成功后跳轉(zhuǎn)到網(wǎng)站后臺(tái),vip用戶登錄成功后跳轉(zhuǎn)到vip頁(yè)面,跳轉(zhuǎn)功能怎么實(shí)現(xiàn)的呢,下面小編給大家?guī)?lái)了Laravel實(shí)現(xiàn)登錄跳轉(zhuǎn)功能,需要的朋友可以參考下2021-08-08

