


Detailed explanation of usage of Zend Framework Action Assistant (Zend_Controller_Action_Helper), zendhelper_PHP tutorial
Detailed explanation of the usage of Zend Framework Action Assistant (Zend_Controller_Action_Helper), zendhelper
This article describes the usage of Zend Framework Action Assistant (Zend_Controller_Action_Helper) with examples. 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 number of derived action controller classes can be minimized. 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()).
Relevant documents 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
│ │
│ └─AutoComplete
│ Abstract.php
│
└─HelperBroker
PriorityStack.php
Common action assistants include :
FlashMessenger is used to handle Flash Messenger sessions;
Json is used to decode and send JSON responses;
Url is used to create Urls;
Redirector provides 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 autocomplete;
ContextSwitch and AjaxContext provide alternative response formats for your actions;
Cache implements cache related operations;
ActionStack is used to operate the action stack.
A few hands-on ways to use instantiation
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.
The assistant broker is used to register assistant objects and assistant paths, obtain assistants and other functions.
Zend_Controller_Action_HelperBroker implementation and list of common methods
<?php /** * @see Zend_Controller_Action_HelperBroker_PriorityStack */ require_once 'Zend/Controller/Action/HelperBroker/PriorityStack.php'; /** * @see Zend_Loader */ require_once 'Zend/Loader.php'; /** * @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 'Zend/Controller/Action/Exception.php'; throw new Zend_Controller_Action_Exception('Invalid plugin loader provided to HelperBroker'); } self::$_pluginLoader = $loader; } /** * Retrieve PluginLoader * * @return Zend_Loader_PluginLoader */ public static function getPluginLoader() { if (null === self::$_pluginLoader) { require_once 'Zend/Loader/PluginLoader.php'; self::$_pluginLoader = new Zend_Loader_PluginLoader(array( 'Zend_Controller_Action_Helper' => 'Zend/Controller/Action/Helper/', )); } return self::$_pluginLoader; } /** * addPrefix() - Add repository of helpers by prefix * * @param string $prefix */ static public function addPrefix($prefix) { $prefix = rtrim($prefix, '_'); $path = str_replace('_', 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 'Zend_Controller_Action_Helper' * @return void */ static public function addPath($path, $prefix = 'Zend_Controller_Action_Helper') { 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 'Zend/Controller/Action/Exception.php'; throw new Zend_Controller_Action_Exception('Action helper "' . $name . '" has not been registered with the helper broker'); } 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, 'direct')) { require_once 'Zend/Controller/Action/Exception.php'; throw new Zend_Controller_Action_Exception('Helper "' . $method . '" does not support overloading via direct()'); } return call_user_func_array(array($helper, 'direct'), $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, '_') !== false) { $name = str_replace(' ', '', ucwords(str_replace('_', ' ', $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 'Zend/Controller/Action/Exception.php'; throw new Zend_Controller_Action_Exception('Action Helper by name ' . $name . ' not found', 0, $e); } $helper = new $class(); if (!$helper instanceof Zend_Controller_Action_Helper_Abstract) { require_once 'Zend/Controller/Action/Exception.php'; throw new Zend_Controller_Action_Exception('Helper name ' . $name . ' -> class ' . $class . ' is not of type Zend_Controller_Action_Helper_Abstract'); } self::getStack()->push($helper); } }
Common usage of assistant broker:
1. Register an assistant
1.
Zend_Controller_Action_HelperBroker::addHelper($helper);
2. Use the addPrefix() method with a class prefix parameter to add the path to the custom helper class.
The prefix is required to follow Zend Framework's class naming convention.
// Add helpers prefixed with My_Action_Helpers in My/Action/Helpers/ Zend_Controller_Action_HelperBroker::addPrefix('My_Action_Helpers');
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('./Plugins/Helpers', 'Helper');
2. Whether the Interpretation Assistant exists
Use the hasHelper($name) method to determine whether an assistant exists in the assistant broker. $name is the short name of the assistant (with the prefix removed):
// Check if 'redirector' helper is registered with the broker: if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) { echo 'Redirector helper registered'; }
There are two static methods to get the helper from the helper 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 helper (with the prefix removed).
// Check if 'redirector' helper is registered with the broker, and fetch: if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) { $redirector = Zend_Controller_Action_HelperBroker::getExistingHelper('redirector'); } // Or, simply retrieve it, not worrying about whether or not it was // previously registered: $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); }
3. removeHelper($name) deletes an assistant in the assistant broker, $name is the short name of the assistant .
// Conditionally remove the 'redirector' helper from the broker: if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) { Zend_Controller_Action_HelperBroker::removeHelper('redirector') }
更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
您可能感兴趣的文章:
- Zend Framework教程之路由功能Zend_Controller_Router详解
- Zend Framework教程之Zend_Controller_Plugin插件用法详解
- Zend Framework教程之响应对象的封装Zend_Controller_Response实例详解
- Zend Framework教程之请求对象的封装Zend_Controller_Request实例详解
- Zend Framework教程之动作的基类Zend_Controller_Action详解
- Zend Framework教程之分发器Zend_Controller_Dispatcher用法详解
- Zend Framework教程之前端控制器Zend_Controller_Front用法详解
- Zend Framework教程之MVC框架的Controller用法分析

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

.NET Framework 4 is required by developers and end users to run the latest versions of applications on Windows. However, while downloading and installing .NET Framework 4, many users complained that the installer stopped midway, displaying the following error message - " .NET Framework 4 has not been installed because Download failed with error code 0x800c0006 ". If you are also experiencing it while installing .NETFramework4 on your device then you are at the right place

Whenever your Windows 11 or Windows 10 PC has an upgrade or update issue, you will usually see an error code indicating the actual reason behind the failure. However, sometimes confusion can arise when an upgrade or update fails without an error code being displayed. With handy error codes, you know exactly where the problem is so you can try to fix it. But since no error code appears, it becomes challenging to identify the issue and resolve it. This will take up a lot of your time to simply find out the reason behind the error. In this case, you can try using a dedicated tool called SetupDiag provided by Microsoft that helps you easily identify the real reason behind the error.
![SCNotification has stopped working [5 steps to fix it]](https://img.php.cn/upload/article/000/887/227/168433050522031.png?x-oss-process=image/resize,m_fill,h_207,w_330)
As a Windows user, you are likely to encounter SCNotification has stopped working error every time you start your computer. SCNotification.exe is a Microsoft system notification file that crashes every time you start your PC due to permission errors and network failures. This error is also known by its problematic event name. So you might not see this as SCNotification having stopped working, but as bug clr20r3. In this article, we will explore all the steps you need to take to fix SCNotification has stopped working so that it doesn’t bother you again. What is SCNotification.e

Microsoft Windows users who have installed Microsoft.NET version 4.5.2, 4.6, or 4.6.1 must install a newer version of the Microsoft Framework if they want Microsoft to support the framework through future product updates. According to Microsoft, all three frameworks will cease support on April 26, 2022. After the support date ends, the product will not receive "security fixes or technical support." Most home devices are kept up to date through Windows updates. These devices already have newer versions of frameworks installed, such as .NET Framework 4.8. Devices that are not updating automatically may

It's been a week since we talked about the new safe mode bug affecting users who installed KB5012643 for Windows 11. This pesky issue didn't appear on the list of known issues Microsoft posted on launch day, thus catching everyone by surprise. Well, just when you thought things couldn't get any worse, Microsoft drops another bomb for users who have installed this cumulative update. Windows 11 Build 22000.652 causes more problems So the tech company is warning Windows 11 users that they may experience problems launching and using some .NET Framework 3.5 applications. Sound familiar? But please don't be surprised

How to use ACL (AccessControlList) for permission control in Zend Framework Introduction: In a web application, permission control is a crucial function. It ensures that users can only access the pages and features they are authorized to access and prevents unauthorized access. The Zend framework provides a convenient way to implement permission control, using the ACL (AccessControlList) component. This article will introduce how to use ACL in Zend Framework

PHP implementation framework: ZendFramework introductory tutorial ZendFramework is an open source website framework developed by PHP and is currently maintained by ZendTechnologies. ZendFramework adopts the MVC design pattern and provides a series of reusable code libraries to serve the implementation of Web2.0 applications and Web Serve. ZendFramework is very popular and respected by PHP developers and has a wide range of

According to news on December 9, Cooler Master recently demonstrated a mini chassis kit in cooperation with notebook modular solution provider Framework at a demonstration event at the Taipei Compute Show. The unique thing about this kit is that it can be compatible with and Install the motherboard from the framework notebook. Currently, this product has begun to be sold on the market, priced at 39 US dollars, which is equivalent to approximately 279 yuan at the current exchange rate. The model number of this chassis kit is named "frameWORKMAINBOARDCASE". In terms of design, it embodies the ultimate compactness and practicality, measuring only 297x133x15 mm. Its original design is to be able to seamlessly connect to framework notebooks
