Heim  >  Artikel  >  php教程  >  Ausführliche Erläuterung der Anwendungsbeispiele des Zend Framework Action Assistant Redirector

Ausführliche Erläuterung der Anwendungsbeispiele des Zend Framework Action Assistant Redirector

高洛峰
高洛峰Original
2017-01-03 13:24:281415Durchsuche

Das Beispiel in diesem Artikel beschreibt die Verwendung des Zend Framework Action Assistant Redirector. Teilen Sie es wie folgt mit allen zu Referenzzwecken:

Redirector bietet eine weitere Implementierungsmethode, um das Programm bei der Umleitung auf interne oder externe Seiten zu unterstützen.

Der Redirector-Assistent (Redirector) ermöglicht Ihnen die Verwendung von a Das Redirector-Objekt hilft dem Programm, auf eine neue URL umzuleiten. Sie bietet mehrere Vorteile gegenüber der Methode _redirect(). Sie können beispielsweise das Verhalten der gesamten Site im Redirector-Objekt vorkonfigurieren oder die Schnittstelle gotoSimple($action, $controller, $module, $params) ähnlich wie Zend_Controller_Action::_forward() verwenden.

Der Redirector verfügt über eine Reihe von Methoden, die sich auf das Umleitungsverhalten auswirken:

setCode() legt den HTTP-Antwortcode fest, der während des Umleitungsprozesses verwendet wird.

setExit() erzwingt die Methode exit() nach der Umleitung. Standardmäßig festgelegt.

setGotoSimple() legt die Standard-URL fest und leitet zur URL weiter, wenn der gotoSimple()-Methode keine Parameter bereitgestellt werden. Sie können eine API ähnlich wie Zend_Controller_Action::_forward() verwenden: setGotoSimple($action, $controller = null, $module = null, array $params = array());

setGotoRoute() Einstellungen basierend auf eine registrierte Router-URL. Durch die Übergabe eines Schlüssel/Wert-Arrays und eines Routernamens werden die URLs basierend auf dem Typ und der Definition des Routers organisiert.

setGotoUrl() legt die Standard-URL fest. Wenn keine Parameter an gotoUrl() übergeben werden, wird die URL verwendet. Akzeptiert eine einzelne URL-Zeichenfolge.

setPrependBase() fügt die Basis-URL des Anforderungsobjekts vor der durch setGotoUrl(), gotoUrl() oder gotoUrlAndExit() angegebenen URL hinzu.

setUseAbsoluteUri() zwingt den Redirector, bei der Umleitung einen absoluten URI zu verwenden. Wenn diese Option festgelegt ist, werden $_SERVER['HTTP_HOST'], $_SERVER['SERVER_PORT'] und $_SERVER['HTTPS'] sowie die von der Umleitungsmethode angegebene URL verwendet, um einen vollständigen URI zu bilden. Diese Option ist derzeit standardmäßig deaktiviert und wird in einer zukünftigen Version möglicherweise standardmäßig aktiviert.

Darüber hinaus gibt es im Redirector unzählige Methoden, um die eigentliche Umleitung durchzuführen.

gotoSimple() verwendet setGotoSimple() (eine API ähnlich _forward()), um die URL zu erstellen und die Umleitung durchzuführen.

gotoRoute() verwendet setGotoRoute() (Route Assembly Route-Assembly), um die URL zu erstellen und die Umleitung durchzuführen.

gotoUrl() verwendet die URL-Zeichenfolge setGotoUrl(), um die URL zu erstellen und die Umleitung durchzuführen.
Abschließend können Sie jederzeit mit getRedirectUrl() die aktuelle Weiterleitungs-URL ermitteln.

Grundlegender Anwendungsfall

Beispiel Nr. 5 Einstellungsoptionen

In diesem Beispiel werden mehrere Optionen geändert, einschließlich der Einstellung des HTTP-Statuscodes, der bei der Umleitung auf 303 verwendet wird. Die Umleitung wird standardmäßig nicht beendet und eine Standard-URL für die Umleitung definiert.

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
  }
}

Beispiel #6 Standardeinstellungen verwenden

In diesem Beispiel wird davon ausgegangen, dass die Standardeinstellungen verwendet werden, was bedeutet, dass alle Weiterleitungen Ursachen haben sofortiger Ausstieg.

// 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
  }
}

Beispiel #7 Verwendung der _forward()-API von goto()

gotoSimple()s API simuliert Zend_Controller_Action: : _nach vorne(). Der Hauptunterschied besteht darin, dass die URL aus den übergebenen Parametern erstellt wird, wobei das Standardformat des Standardrouters verwendet wird: module/:controller/:action/*. Dann umleiten, anstatt die Aktionskettenschleife fortzusetzen.

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

Beispiel Nr. 8 Verwenden der Routenassemblierung über gotoRoute()

Das folgende Beispiel verwendet die assemble( )-Methode des Routers und erstellt eine URL basierend auf einem assoziativen Array übergebener Parameter. Gehen Sie davon aus, dass die folgende Route registriert wurde:

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

Gegeben ein Array, das Jahr ist 2006, der Monat ist 4, das Datum ist 24 und Die ID ist 42. Auf dieser Grundlage kann die URL/blog/2006/4/24/42 zusammengestellt werden.

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

Der Quellcode von Zend_Controller_Action_Helper_Redirector.

Es ist nicht schwer, die Implementierungsmethode und allgemeine Verwendungsmethoden anhand des Quellcodes zu erkennen.

<?php
/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once &#39;Zend/Controller/Action/Helper/Abstract.php&#39;;
/**
 * @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&#39;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 &#39;Zend/Controller/Action/Exception.php&#39;;
      throw new Zend_Controller_Action_Exception(&#39;Invalid redirect HTTP status code (&#39; . $code . &#39;)&#39;);
    }
    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 &#39;prepend base&#39; 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(&#39;#^(https?|ftp)://#&#39;, $url)) {
      $host = (isset($_SERVER[&#39;HTTP_HOST&#39;])?$_SERVER[&#39;HTTP_HOST&#39;]:&#39;&#39;);
      $proto = (isset($_SERVER[&#39;HTTPS&#39;])&&$_SERVER[&#39;HTTPS&#39;]!=="off") ? &#39;https&#39; : &#39;http&#39;;
      $port = (isset($_SERVER[&#39;SERVER_PORT&#39;])?$_SERVER[&#39;SERVER_PORT&#39;]:80);
      $uri  = $proto . &#39;://&#39; . $host;
      if (((&#39;http&#39; == $proto) && (80 != $port)) || ((&#39;https&#39; == $proto) && (443 != $port))) {
        // do not append if HTTP_HOST already contains port
        if (strrchr($host, &#39;:&#39;) === false) {
          $uri .= &#39;:&#39; . $port;
        }
      }
      $url = $uri . &#39;/&#39; . ltrim($url, &#39;/&#39;);
    }
    $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(), &#39;/&#39;);
        if (!empty($base) && (&#39;/&#39; != $base)) {
          $url = $base . &#39;/&#39; . ltrim($url, &#39;/&#39;);
        } else {
          $url = &#39;/&#39; . ltrim($url, &#39;/&#39;);
        }
      }
    }
    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 = &#39;&#39;;
    }
    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, &#39;default&#39;, 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"), &#39;&#39;, $url);
    if (null !== $options) {
      if (isset($options[&#39;exit&#39;])) {
        $this->setExit(($options[&#39;exit&#39;]) ? true : false);
      }
      if (isset($options[&#39;prependBase&#39;])) {
        $this->setPrependBase(($options[&#39;prependBase&#39;]) ? true : false);
      }
      if (isset($options[&#39;code&#39;])) {
        $this->setCode($options[&#39;code&#39;]);
      }
    }
    // If relative URL, decide if we should prepend base URL
    if (!preg_match(&#39;|^[a-z]+://|&#39;, $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&#39;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&#39;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(&#39;Zend_Session&#39;, 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 &#39;goto&#39;, &#39;setGoto&#39;, and &#39;gotoAndExit&#39; 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 (&#39;goto&#39; == $method) {
      return call_user_func_array(array($this, &#39;gotoSimple&#39;), $args);
    }
    if (&#39;setgoto&#39; == $method) {
      return call_user_func_array(array($this, &#39;setGotoSimple&#39;), $args);
    }
    if (&#39;gotoandexit&#39; == $method) {
      return call_user_func_array(array($this, &#39;gotoSimpleAndExit&#39;), $args);
    }
    require_once &#39;Zend/Controller/Action/Exception.php&#39;;
    throw new Zend_Controller_Action_Exception(sprintf(&#39;Invalid method "%s" called on redirector&#39;, $method));
  }
}

Ich hoffe, dieser Artikel wird für alle hilfreich sein, die sich mit PHP-Programmierung befassen.

Ausführlichere Anwendungsbeispiele für den Zend Framework Action Assistant Redirector und verwandte Artikel finden Sie auf der chinesischen PHP-Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn