>  기사  >  php教程  >  Zend Framework Action Assistant Redirector의 사용 예에 ​​대한 자세한 설명

Zend Framework Action Assistant Redirector의 사용 예에 ​​대한 자세한 설명

高洛峰
高洛峰원래의
2017-01-03 13:24:281415검색

이 기사의 예에서는 Zend Framework Action Assistant Redirector의 사용법을 설명합니다. 다음과 같이 참조용으로 모든 사람과 공유하십시오.

리디렉터는 프로그램이 내부 또는 외부 페이지로 리디렉션되는 데 도움이 되는 또 다른 구현 방법을 제공합니다.

리디렉터(리디렉터) 도우미를 사용하면 리디렉터 개체는 프로그램이 새 URL로 리디렉션되도록 도와줍니다. _redirect() 메서드에 비해 몇 가지 장점이 있습니다. 예를 들어, 리디렉터 개체에서 전체 사이트의 동작을 미리 구성하거나 Zend_Controller_Action::_forward()와 유사한 gotoSimple($action, $controller, $module, $params) 인터페이스를 사용할 수 있습니다.

리디렉터에는 리디렉션 동작에 영향을 미치는 여러 메서드가 있습니다.

setCode()는 리디렉션 프로세스 중에 사용되는 HTTP 응답 코드를 설정합니다.

setExit()는 리디렉션 후 종료() 메서드를 강제 실행합니다. 기본적으로 설정됩니다.

setGotoSimple()은 기본 URL을 설정하고 gotoSimple() 메서드에 매개변수가 제공되지 않으면 해당 URL로 리디렉션합니다. Zend_Controller_Action::_forward()와 유사한 API를 사용할 수 있습니다. setGotoSimple($action, $controller = null, $module = null, array $params = array());

setGotoRoute() 설정을 기반으로 합니다. 등록된 라우터 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을 시뮬레이션합니다. _앞으로(). 주요 차이점은 기본 라우터의 기본 형식(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()를 통해 경로 어셈블리 사용

다음 예에서는 라우터의 assemble( ) 메서드를 사용하여 전달된 매개변수의 연관 배열을 기반으로 하는 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 Action Assistant Redirector의 자세한 사용예와 관련 글은 PHP 중국어 홈페이지를 참고해주세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.