ホームページ  >  記事  >  php教程  >  Zend FrameworkのアクションアシスタントRedirectorの使用例を詳しく解説

Zend FrameworkのアクションアシスタントRedirectorの使用例を詳しく解説

高洛峰
高洛峰オリジナル
2017-01-03 13:24:281415ブラウズ

この記事の例では、Zend Framework のアクション アシスタント リダイレクターの使用法について説明します。以下のように、参考として全員と共有してください。

リダイレクターは、プログラムが内部ページまたは外部ページにリダイレクトできるようにするための別の実装メソッドを提供します。

リダイレクター (リダイレクター) アシスタントを使用すると、プログラムが次のページにリダイレクトできるようにします。新しい 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 を設定しますルーター。キー/値の配列とルーター名を渡すことにより、ルーターのタイプと定義に基づいて URL が整理されます。

setGotoUrl() はデフォルトの URL を設定します。パラメータが gotoUrl() に渡されない場合、この URL が使用されます。単一の URL 文字列を受け入れます。

setPrependBase() は、setGotoUrl()、gotoUrl()、または gotoUrlAndExit() で指定された URL の前にリクエスト オブジェクトのベース URL を追加します。

setUseAbsoluteUri() は、リダイレクト時にリダイレクターに絶対 URI を使用するように強制します。このオプションを設定すると、$_SERVER['HTTP_HOST']、$_SERVER['SERVER_PORT']、$_SERVER['HTTPS']、およびリダイレクト メソッドで指定された URL が完全な URI の形成に使用されます。このオプションは現在デフォルトでオフになっていますが、将来のリリースではデフォルトでオンになる可能性があります。

さらに、リダイレクターには実際のリダイレクトを実行するためのメソッドがたくさんあります。

gotoSimple() は、setGotoSimple() (_forward() に似た API) を使用して URL を構築し、リダイレクトを実行します。

gotoRoute() は setGotoRoute() (ルート アセンブリ ルートアセンブリ) を使用して URL を構築し、リダイレクトを実行します。

gotoUrl() は setGotoUrl() URL 文字列) を使用して URL を構築し、リダイレクトを実行します。
最後に、getRedirectUrl() を使用していつでも現在のリダイレクト URL を確認できます。

基本的な使用例

例 #5 オプションの設定

この例では、303 へのリダイレクト時に使用される HTTP ステータス コードの設定、リダイレクト時にデフォルトで終了しないこと、リダイレクトを使用するためのデフォルト 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
  }
}

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

例 7 goto() の _forward()API

gotoSimple() の API を使用して Zend_Controller_Action::_forward() をシミュレートします。主な違いは、デフォルト ルーターのデフォルト形式 module/:controller/:action/* を使用して、渡されたパラメーターから URL を構築することです。次に、アクション チェーン ループを続行する代わりにリダイレクトします。

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

例 #8 gotoRoute() でルート アセンブリを使用する

次の例では、ルーターの Assembly() メソッドを使用して、渡されたパラメーターの連想配列に基づいて 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 &#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));
  }
}

この記事が PHP プログラミングの皆様のお役に立てれば幸いです。

Zend Framework アクション アシスタント リダイレクターの詳細な使用例と関連記事については、PHP 中国語 Web サイトに注目してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。