Zend Framework Action Assistant Redirector Usage Example _php example

Source: Internet
Author: User
Tags goto mixed response code uri flag zend zend framework

This example describes the Zend Framework action Assistant redirector usage. Share to everyone for your reference, specific as follows:

Redirector provides another way to implement the Help program to redirect to internal or external pages;

The steering Gear (redirector) assistant lets you redirect to a new URL using a Redirector Object helper program. Compared with the _redirect () method, it has many advantages. For example, it is possible to pre-configured the entire site in the redirector object, or to use a similar gotosimple ($action, $controller, $module, $ zend_controller_action::_forward (). params) interface.

A redirector has a number of methods that affect redirect behavior:

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

Setexit () enforces the exit () method after redirection. Default is set.

Setgotosimple () sets the default URL, which is turned to when no arguments are supplied to the Gotosimple () method. You can use a api:setgotosimple like Zend_controller_action::_forward () ($action, $controller = null, $module = NULL, array $params = Array ());

Setgotoroute () sets the URL based on a registered router. By passing in a key/value array and a router name, it organizes the URL based on the type and definition of the router.

Setgotourl () sets the default URL, which is used when no arguments are passed in to Gotourl (). Accepts a single URL string.

Setprependbase () in front of the URL specified by Setgotourl (), Gotourl (), or Gotourlandexit (), joins the base URL of the requested object.

Setuseabsoluteuri () forces the redirector to use an absolute URI when redirecting. When this option is set, a complete URI is formed using the URL specified by $_server[' http_host ', $_server[' server_port ' and $_server[' HTTPS ', and the redirection method. This option is currently closed by default, and future versions may be turned on by default.

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

Gotosimple () uses Setgotosimple () (similar to _forward () APIs) to build URLs and perform redirects.

Gotoroute () uses Setgotoroute () (Routing assembly route-assembly) to build URLs and perform redirects.

Gotourl () uses the Setgotourl () URL string) to construct the URL and perform the redirection.
Finally, you can use Getredirecturl () at any time to determine the current redirection URL.

Basic Use Cases

Example #5 Setting options

This example changes several options, including the HTTP status code used when setting redirects to 303, not exiting by default when redirecting, and defining the default URL for redirection.

Class Somecontroller extends Zend_controller_action
{
  /**
   * redirector-defined for code completion
   *< c5/>* @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" helper broker, these
    //b Ecome relevant for the 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 a E XIT
    //to occur as done:
    $this->_redirector->redirectandexit ();
    Return Never reached
  }
}

Example #6 Use default settings

This example assumes that using default settings means that any redirection will result in an immediate exit.

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 the _forward () API using Goto ()

The Gotosimple () ' s API simulates Zend_controller_action::_forward (). The main difference is that it constructs the URL via the parameters passed in, using the default router's default 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 ' ' My-controller ' in the
    Curre NT
    //module, using the params param1 => test and param2 => test2
    $this->_redirector->gotosimple (' m Y-action ',
    ' My-controller ',
    null,
    array (' param1 ' => ' test ',
       ' param2 ' => ' test2 '
       )
    );
  }
}

Example #8 Gotoroute () using Routing assembly (route assembly)

The following example uses the router's assemble () method to create a URL based on an associative array of incoming parameters. Assume that the following routes have been registered:

$route = new Zend_controller_router_route (
  ' blog/:year/:month/:d ay/:id ',
  array (' Controller ' => ' archive ') ,
     ' module ' => ' blog ',
     ' action ' => ' view ')
;
$router->addroute (' blogarchive ', $route);

Given an array, where the year is 2006, the month is 4, and the date is 24,id to 42, the URL/BLOG/2006/4/24/42 can be assembled accordingly.

Class Blogadmincontroller extends Zend_controller_action
{
  /**
   * redirector-defined for code completion< c4/>*
   * @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 (
      ' Year ' = > 2006,
         ' Month ' => 4,
         ' Day ' =>,
         ' id ' => ',
      ' blogarchive '
  }


Zend_controller_action_helper_redirector's source code.

The source code is not difficult to see the implementation method, as well as common use 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 = Tru
  E 
   /** * 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 a absolute URI when redirecting * @var boolean/protected $_useabsoluteuri = false; /** * Whether or not to close the session before exiting * @var boolean/protected $_closesessiononexit = Tru
  E /** * Retrieve HTTP status code to emit in {@link _redirect ()} call * * @return int/Public Function Getco
  De () {return $this->_code; }/** * Validate HTTP Status REDIRECT code * * @param int $code * @throws zend_controller_action_exception o
    N Invalid HTTP status code * @return True */protected function _checkcode ($code) {$code = (int) $code; if (> $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 ()} 'll exit when finished.
  * * @return Boolean/Public Function Getexit () {return $this->_exit; }/** * Retrieve exit flag for {@link _redirect ()} behaviour * * @param boolean $flag * @return Zend_control Ler_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 ()} to 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 Setpre
    Pendbase ($flag) {$this->_prependbase = ($flag)? True:false;
  return $this;
   /** * Retrieve flag for whether or does {@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 the close of session before exiting. * @param boolean $flag * @return Zend_controller_action_helper_redirector provides a fluent interface * * Publ
    IC function Setclosesessiononexit ($flag) {$this->_closesessiononexit = ($flag)? True:false;
  return $this; /** * Return use absolute URI flag * * @return Boolean/Public Function Getuseabsoluteuri () {RE
  Turn $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) && (!= $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 * @ret Urn 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 ()) {$dispat
    Cher = $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 * @pa Ram 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 the Request object if URL is relative, and halts script execution by * calling exit (). * $options is a optional associative array that can used to control * RedIrect behaviour.  The available option keys are: *-Exit:boolean flag indicating whether or not to halt script execution as 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 and 307. * * _redirect () sets the Location header in the response object.
   If you are set * the exit flag to False, your can override this header later in code * execution.
   * * If is true by default, _redirect () would write and * close the "session", if any. * @param string $url * @param array $options * @return void/Public Function setgotourl ($url, array $opt
    ions = 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)) {$u
    RL = $this->_prependbase ($url);
  $this->_redirect ($url); /** * Perform a redirect to a action/controller/module with params * * @param string $action * @param str ing $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 a action/controller/module with params, forcing a immdiate exit * * @param Mixed $actIon * @param mixed $controller * @param mixed $module * @param array $params * @return void */Public fun Ction gotosimpleandexit ($action, $controller = null, $module = NULL, array $params = Array ()) {$this->setgotosim
    Ple ($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 Boolea N $reset * @param boolean $encode * @return void */Public Function Gotoroute (array $urlOptions = Array (), $nam
    E = 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 Boolea n $reset * @return void/Public Function gotorouteandexit (array $urlOptions = Array (), $name = null, $reset = FA
    LSE) {$this->setgotoroute ($urlOptions, $name, $reset);
  $this->redirectandexit ();
  /** * Perform a redirect to a URL * * @param string $url * @param array $options * @return void * * * *
    The 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 $para
  MS * @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 * @par Am Array $args * @return mixed * @throws zend_controller_action_exception for invalid methods/public functio
    N __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));

 }
}

More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design.

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.