search
HomeBackend DevelopmentPHP TutorialUsage analysis of Zend Framework action assistant

Usage analysis of Zend Framework action assistant

Jun 15, 2018 am 11:11 AM
frameworkzend

This article mainly introduces the usage of the Zend Framework action assistant (Zend_Controller_Action_Helper), and analyzes in detail the function, definition, usage and related implementation code of the action assistant Zend_Controller_Action_Helper. Friends in need can refer to the following

Examples of this article Learned the usage of Zend Framework action helper (Zend_Controller_Action_Helper). Share it with everyone for your reference, the details are as follows:

Through the assistant mode, some frequently used functional modules can be encapsulated, so that they can be used flexibly where needed, mainly in actions.

There are two kinds of helpers in Zend Framework, action assistant (Zend_Controller_Action_Helper) and view assistant (Zend_View_Helper).

The action assistant can instantly add functions (runtime and/or on-demand functionality) to any derived action controller of Zend_Controller_Action, so that when adding public action controller functions, the derived action control can be minimized. Device class is necessary.

The action helper is loaded when it needs to be called, and can be instantiated when requested (bootstrap) or when the action controller is created (init()).

Related files involved

In /library/Zend/Controller/Action/

│ Exception.php
│ HelperBroker.php
│ Interface .php

├─Helper
│ │ Abstract.php
│ │ ActionStack.php
│ │ AjaxContext.php
│ │ AutoCompleteDojo.php
│ │ AutoCompleteScriptaculous .php
│ │ Cache.php
│ │ ContextSwitch.php
│ │ FlashMessenger.php
│ │ Json.php
│ │ Redirector.php
│ │ Url.php
│ │ ViewRenderer.php
# │ │
│ a ─ Autocomplete
│ Abstract.php

─ Heelperbroker
PriorityStock.php




This ##Common action assistants are
:

FlashMessenger is used to process Flash Messenger sessions;
Json is used to decode and send JSON responses;
Url is used to create Urls;

Redirector Provide another implementation method to help the program redirect to internal or external pages;

ViewRenderer automatically completes the process of establishing a view object in the controller and rendering the view; AutoComplete automatically responds to AJAX's automatic completion; ContextSwitch and AjaxContext provide alternative response formats for your actions;

Cache implements cache-related operations;

ActionStack is used to operate the action stack.

Several hands-on instantiation methods

1. Through the getHelper() method of the $_helper member of Zend_Controller_Action

. Just call getHelper() directly and pass in the name of the helper.

$redirector = $this->_helper->getHelper('Redirector');
//$redirector->getName();
$redirector->gotoSimple('index2');

2. Directly access the helper object

corresponding to the attribute of the _helper assistant.

$redirector = $this->_helper->Redirector;

Zend_Controller_Action_HelperBroker

The Chinese name is translated as "Assistant Broker", as the name suggests, it is the middleman of the action assistant.

The second way to instantiate an action is through the magic method __get() of Zend_Controller_Action_HelperBroker.

Assistant broker is used to register assistant objects and assistant paths and obtain assistants and other functions.

Zend_Controller_Action_HelperBroker implementation and list of common methods

<?php
/**
 * @see Zend_Controller_Action_HelperBroker_PriorityStack
 */
require_once &#39;Zend/Controller/Action/HelperBroker/PriorityStack.php&#39;;
/**
 * @see Zend_Loader
 */
require_once &#39;Zend/Loader.php&#39;;
/**
 * @category  Zend
 * @package  Zend_Controller
 * @subpackage Zend_Controller_Action
 * @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_HelperBroker
{
  /**
   * $_actionController - ActionController reference
   *
   * @var Zend_Controller_Action
   */
  protected $_actionController;
  /**
   * @var Zend_Loader_PluginLoader_Interface
   */
  protected static $_pluginLoader;
  /**
   * $_helpers - Helper array
   *
   * @var Zend_Controller_Action_HelperBroker_PriorityStack
   */
  protected static $_stack = null;
  /**
   * Set PluginLoader for use with broker
   *
   * @param Zend_Loader_PluginLoader_Interface $loader
   * @return void
   */
  public static function setPluginLoader($loader)
  {
    if ((null !== $loader) && (!$loader instanceof Zend_Loader_PluginLoader_Interface)) {
      require_once &#39;Zend/Controller/Action/Exception.php&#39;;
      throw new Zend_Controller_Action_Exception(&#39;Invalid plugin loader provided to HelperBroker&#39;);
    }
    self::$_pluginLoader = $loader;
  }
  /**
   * Retrieve PluginLoader
   *
   * @return Zend_Loader_PluginLoader
   */
  public static function getPluginLoader()
  {
    if (null === self::$_pluginLoader) {
      require_once &#39;Zend/Loader/PluginLoader.php&#39;;
      self::$_pluginLoader = new Zend_Loader_PluginLoader(array(
        &#39;Zend_Controller_Action_Helper&#39; => &#39;Zend/Controller/Action/Helper/&#39;,
      ));
    }
    return self::$_pluginLoader;
  }
  /**
   * addPrefix() - Add repository of helpers by prefix
   *
   * @param string $prefix
   */
  static public function addPrefix($prefix)
  {
    $prefix = rtrim($prefix, &#39;_&#39;);
    $path  = str_replace(&#39;_&#39;, DIRECTORY_SEPARATOR, $prefix);
    self::getPluginLoader()->addPrefixPath($prefix, $path);
  }
  /**
   * addPath() - Add path to repositories where Action_Helpers could be found.
   *
   * @param string $path
   * @param string $prefix Optional; defaults to &#39;Zend_Controller_Action_Helper&#39;
   * @return void
   */
  static public function addPath($path, $prefix = &#39;Zend_Controller_Action_Helper&#39;)
  {
    self::getPluginLoader()->addPrefixPath($prefix, $path);
  }
  /**
   * addHelper() - Add helper objects
   *
   * @param Zend_Controller_Action_Helper_Abstract $helper
   * @return void
   */
  static public function addHelper(Zend_Controller_Action_Helper_Abstract $helper)
  {
    self::getStack()->push($helper);
    return;
  }
  /**
   * resetHelpers()
   *
   * @return void
   */
  static public function resetHelpers()
  {
    self::$_stack = null;
    return;
  }
  /**
   * Retrieve or initialize a helper statically
   *
   * Retrieves a helper object statically, loading on-demand if the helper
   * does not already exist in the stack. Always returns a helper, unless
   * the helper class cannot be found.
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   */
  public static function getStaticHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (!isset($stack->{$name})) {
      self::_loadHelper($name);
    }
    return $stack->{$name};
  }
  /**
   * getExistingHelper() - get helper by name
   *
   * Static method to retrieve helper object. Only retrieves helpers already
   * initialized with the broker (either via addHelper() or on-demand loading
   * via getHelper()).
   *
   * Throws an exception if the referenced helper does not exist in the
   * stack; use {@link hasHelper()} to check if the helper is registered
   * prior to retrieving it.
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   * @throws Zend_Controller_Action_Exception
   */
  public static function getExistingHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (!isset($stack->{$name})) {
      require_once &#39;Zend/Controller/Action/Exception.php&#39;;
      throw new Zend_Controller_Action_Exception(&#39;Action helper "&#39; . $name . &#39;" has not been registered with the helper broker&#39;);
    }
    return $stack->{$name};
  }
  /**
   * Return all registered helpers as helper => object pairs
   *
   * @return array
   */
  public static function getExistingHelpers()
  {
    return self::getStack()->getHelpersByName();
  }
  /**
   * Is a particular helper loaded in the broker?
   *
   * @param string $name
   * @return boolean
   */
  public static function hasHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    return isset(self::getStack()->{$name});
  }
  /**
   * Remove a particular helper from the broker
   *
   * @param string $name
   * @return boolean
   */
  public static function removeHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (isset($stack->{$name})) {
      unset($stack->{$name});
    }
    return false;
  }
  /**
   * Lazy load the priority stack and return it
   *
   * @return Zend_Controller_Action_HelperBroker_PriorityStack
   */
  public static function getStack()
  {
    if (self::$_stack == null) {
      self::$_stack = new Zend_Controller_Action_HelperBroker_PriorityStack();
    }
    return self::$_stack;
  }
  /**
   * Constructor
   *
   * @param Zend_Controller_Action $actionController
   * @return void
   */
  public function __construct(Zend_Controller_Action $actionController)
  {
    $this->_actionController = $actionController;
    foreach (self::getStack() as $helper) {
      $helper->setActionController($actionController);
      $helper->init();
    }
  }
  /**
   * notifyPreDispatch() - called by action controller dispatch method
   *
   * @return void
   */
  public function notifyPreDispatch()
  {
    foreach (self::getStack() as $helper) {
      $helper->preDispatch();
    }
  }
  /**
   * notifyPostDispatch() - called by action controller dispatch method
   *
   * @return void
   */
  public function notifyPostDispatch()
  {
    foreach (self::getStack() as $helper) {
      $helper->postDispatch();
    }
  }
  /**
   * getHelper() - get helper by name
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   */
  public function getHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (!isset($stack->{$name})) {
      self::_loadHelper($name);
    }
    $helper = $stack->{$name};
    $initialize = false;
    if (null === ($actionController = $helper->getActionController())) {
      $initialize = true;
    } elseif ($actionController !== $this->_actionController) {
      $initialize = true;
    }
    if ($initialize) {
      $helper->setActionController($this->_actionController)
          ->init();
    }
    return $helper;
  }
  /**
   * Method overloading
   *
   * @param string $method
   * @param array $args
   * @return mixed
   * @throws Zend_Controller_Action_Exception if helper does not have a direct() method
   */
  public function __call($method, $args)
  {
    $helper = $this->getHelper($method);
    if (!method_exists($helper, &#39;direct&#39;)) {
      require_once &#39;Zend/Controller/Action/Exception.php&#39;;
      throw new Zend_Controller_Action_Exception(&#39;Helper "&#39; . $method . &#39;" does not support overloading via direct()&#39;);
    }
    return call_user_func_array(array($helper, &#39;direct&#39;), $args);
  }
  /**
   * Retrieve helper by name as object property
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   */
  public function __get($name)
  {
    return $this->getHelper($name);
  }
  /**
   * Normalize helper name for lookups
   *
   * @param string $name
   * @return string
   */
  protected static function _normalizeHelperName($name)
  {
    if (strpos($name, &#39;_&#39;) !== false) {
      $name = str_replace(&#39; &#39;, &#39;&#39;, ucwords(str_replace(&#39;_&#39;, &#39; &#39;, $name)));
    }
    return ucfirst($name);
  }
  /**
   * Load a helper
   *
   * @param string $name
   * @return void
   */
  protected static function _loadHelper($name)
  {
    try {
      $class = self::getPluginLoader()->load($name);
    } catch (Zend_Loader_PluginLoader_Exception $e) {
      require_once &#39;Zend/Controller/Action/Exception.php&#39;;
      throw new Zend_Controller_Action_Exception(&#39;Action Helper by name &#39; . $name . &#39; not found&#39;, 0, $e);
    }
    $helper = new $class();
    if (!$helper instanceof Zend_Controller_Action_Helper_Abstract) {
      require_once &#39;Zend/Controller/Action/Exception.php&#39;;
      throw new Zend_Controller_Action_Exception(&#39;Helper name &#39; . $name . &#39; -> class &#39; . $class . &#39; is not of type Zend_Controller_Action_Helper_Abstract&#39;);
    }
    self::getStack()->push($helper);
  }
}

##Common usage of assistant broker:

1. Register an assistant

1.


Zend_Controller_Action_HelperBroker::addHelper($helper);

2. With a class through the addPrefix() method Prefix parameter, used to add the path of the custom helper class.

Requires the prefix to follow Zend Framework's class naming convention.

// Add helpers prefixed with My_Action_Helpers in My/Action/Helpers/
Zend_Controller_Action_HelperBroker::addPrefix(&#39;My_Action_Helpers&#39;);

3. Use the addPath() method. The first parameter is a directory, and the second parameter is the class prefix (default is 'Zend_Controller_Action_Helper').

is used to map your own class prefix to the specified directory.

// Add helpers prefixed with Helper in Plugins/Helpers/
Zend_Controller_Action_HelperBroker::addPath(&#39;./Plugins/Helpers&#39;,
                       &#39;Helper&#39;);

2. Determine whether the assistant exists

Use the hasHelper($name) method to determine whether the assistant broker exists Whether an assistant exists, $name is the short name of the assistant (with the prefix removed):

// Check if &#39;redirector&#39; helper is registered with the broker:
if (Zend_Controller_Action_HelperBroker::hasHelper(&#39;redirector&#39;)) {
  echo &#39;Redirector helper registered&#39;;
}

There are two static methods to obtain the assistant from the assistant broker: getExistingHelper() and getStaticHelper(). getExistingHelper() will get the helper only if it has been called before or explicitly registered with the helper broker, otherwise it will throw an exception. getStaticHelper() does the same as getExistingHelper(), but if the helper stack has not been registered, it will try to initialize the helper. To get the helper you want to configure, getStaticHelper() is a good choice.

Both methods take one parameter, $name, which is the short name of the assistant (removing the prefix).

// Check if &#39;redirector&#39; helper is registered with the broker, and fetch:
if (Zend_Controller_Action_HelperBroker::hasHelper(&#39;redirector&#39;)) {
  $redirector =
    Zend_Controller_Action_HelperBroker::getExistingHelper(&#39;redirector&#39;);
}
// Or, simply retrieve it, not worrying about whether or not it was
// previously registered:
$redirector =
  Zend_Controller_Action_HelperBroker::getStaticHelper(&#39;redirector&#39;);
}

#########3. removeHelper($name) deletes an assistant in the assistant broker, $name is the short name of the assistant ###. ###

// Conditionally remove the &#39;redirector&#39; helper from the broker:
if (Zend_Controller_Action_HelperBroker::hasHelper(&#39;redirector&#39;)) {
  Zend_Controller_Action_HelperBroker::removeHelper(&#39;redirector&#39;)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Zend Framework校验器Zend_Validate的用法解析

Zend Framework中Zend_View组件的用法解析

The above is the detailed content of Usage analysis of Zend Framework action assistant. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor