ZendFramework action assistant Redirector usage example _ php instance

Source: Internet
Author: User
Tags response code uri flag zend framework
This article mainly introduces ZendFramework action assistant Redirector usage, and analyzes the function, usage, and precautions of the steering Redirector Based on the instance form, for more information about Zend Framework action assistant Redirector, see the following example. We will share this with you for your reference. The details are as follows:

Redirector provides another implementation method to help redirect programs to internal or external pages;

The Redirector assistant allows you to use a steering tool object to redirect programs to a new URL. Compared with the _ redirect () method, it has multiple advantages. For example, you can configure the behavior of the entire site in advance in the steering gear object, or use gotoSimple ($ action, $ controller, $ module, $ params) similar to Zend_Controller_Action: _ forward) interface.

Steering gear has a large number of methods that affect redirection behavior:

SetCode () sets the HTTP response code used during redirection.

SetExit () force the exit () method after redirection. It is set by default.

SetGotoSimple () sets the default URL. This URL is used when no parameter is provided to the gotoSimple () method. You can use APIs like Zend_Controller_Action: _ forward (): setGotoSimple ($ action, $ controller = null, $ module = null, array $ params = array ());

SetGotoRoute () is set based on a registered router URL. You can input a key/value array and a vro name to organize URLs based on the type and definition of the vro.

SetGotoUrl () sets the default URL. This URL is used when no parameter is input to gotoUrl. Accept a single URL string.

SetPrependBase () adds the base address (base URL) of the request object before the URL specified by setGotoUrl (), gotoUrl (), or gotoUrlAndExit ).

SetUseAbsoluteUri () forces the steering gear to use an absolute URI during redirection. When this option is set, the URL specified by $ _ SERVER ['HTTP _ host'], $ _ SERVER ['server _ port'], $ _ SERVER ['https'], and redirect method will be used, to form a complete URI. This option is disabled by default, and may be enabled by default in future versions.

In addition, there are a lot of methods in the steering gear to execute the actual redirection.

GotoSimple () uses setGotoSimple () (similar to the _ forward () API) to construct a URL and perform redirection.

GotoRoute () uses setGotoRoute () (route assembly route-assembly) to construct a URL and perform redirection.

GotoUrl () uses setGotoUrl () URL string) to construct a URL and perform redirection.
Finally, you can use getRedirectUrl () to determine the current Redirection URL at any time.

Basic Use Cases

Example #5 set options

In this example, several options are changed, including setting the HTTP status code 303 for redirection, not exiting by default during redirection, and defining the default URL for redirection.

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 use default settings

This example assumes that the default setting is used, which means that any redirection will cause immediate exit.

// ALTERNATIVE EXAMPLEclass 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 use goto ()'s _ forward () API

The gotoSimple ()'s API simulates Zend_Controller_Action: _ forward (). The main difference is that it constructs a URL through the input parameters and uses the default vro format: module/: controller/: action /*. Then redirect instead of continuing the action chain loop.

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 use route assembly through gotoRoute)

The following example uses the assemble () method of the router to create a URL Based on the correlated array of input parameters. Assume that the following route has been registered:

$route = new Zend_Controller_Router_Route(  'blog/:year/:month/:day/:id',  array('controller' => 'archive',     'module' => 'blog',     'action' => 'view'));$router->addRoute('blogArchive', $route);

Given an array, the year is 2006, the month is 4, the date is 24, and the id is 42. Based on this, you can assemble the 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'    );  }}

Source code of Zend_Controller_Action_Helper_Redirector.

It is not difficult to see the implementation method through the source code, as well as common usage methods.

<?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));  }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.