search
HomeBackend DevelopmentPHP TutorialZend Framework动作助手(Zend_Controller_Action_Helper)用法详解_php实例

本文实例讲述了Zend Framework动作助手(Zend_Controller_Action_Helper)用法。分享给大家供大家参考,具体如下:

通过助手模式,可以把一些经常使用的功能模块做封装,从而在可以在需要的地方灵活使用,主要是在action使用。

Zend Framework中有两种助手,动作助手(Zend_Controller_Action_Helper)和试图助手(Zend_View_Helper)。

动作助手可以向任何Zend_Controller_Action的衍生动作控制器中,即时的加入功能(runtime and/or on-demand functionality),以使得增加公共的动作控制器功能时,尽量减少衍生动作控制器类的必要。

动作助手在需要调用时加载,可以在请求的时候(bootstrap)或者动作控制器创建的时候(init())实例化。

涉及到的相关文件

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

常见的动作助手有

FlashMessenger 用来处理Flash Messenger会话;
Json 用来解码和发送 JSON 响应;
Url  用于创建Urls;
Redirector 提供另一种实现方式,帮助程序重定向到内部或者外部页面;
ViewRenderer 自动的完成在控制器内建立视图对象并渲染视图的过程;
AutoComplete 自动响应 AJAX 的自动完成;
ContextSwitch 和 AjaxContext 为你的动作提供替代响应格式;
Cache  实现cache的相关操作;
ActionStack 用于操作动作堆栈。

动手的几种实例化使用方式

1.通过Zend_Controller_Action的 $_helper成员的getHelper()方法。直接调用getHelper(),传入助手的名称即可。

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

2.直接通过访问的_helper助手的属性对应的助手对象

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

Zend_Controller_Action_HelperBroker

中文名称译作"助手经纪人",顾名思义,是动作助手的中间人。

在动作的实例化使用的方式的第二种方式就是通过Zend_Controller_Action_HelperBroker的魔术方法__get()来实现的。

助手经纪人用于注册助手对象和助手路径以及获取助手等等功能。

Zend_Controller_Action_HelperBroker的实现以及常用方法列表

<&#63;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&#63;
   *
   * @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);
  }
}

助手经纪人的常见用法:

一、注册一个助手

1.

Zend_Controller_Action_HelperBroker::addHelper($helper);

2.通过addPrefix()方法带有一个类前缀参数,用来加入自定义助手类的路径。
要求前缀遵循Zend Framework的类命名惯例。

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

3.使用addPath()方法第一个参数为一个目录,第二个为类前缀(默认为'Zend_Controller_Action_Helper')。

用来将自己的类前缀映射到指定的目录。

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

二、判读助手是否存在

使用hasHelper($name)方法来判定助手经纪人中是否存在某助手,$name是助手的短名称(去掉前缀的):

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

从助手经纪人中获取助手有两个静态方法:getExistingHelper() 和 getStaticHelper() 。getExistingHelper()将获取助手仅当它以前调用过或者显性地通过助手经纪人注册过,否则就抛出一个异常。getStaticHelper() 的做法和getExistingHelper()一样,但如果还没有注册助手堆栈,它将尝试初始化助手,为获取你要配置的的助手,getStaticHelper()是一个好的选择。

两个方法都带一个参数,$name,它是助手的短名称(去掉前缀)。

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

三、removeHelper($name)删除助手经纪人中的某个助手,$name是助手的短名称

// 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程序设计有所帮助。

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
Microsoft NET Framework 安装问题 错误代码 0x800c0006 修复Microsoft NET Framework 安装问题 错误代码 0x800c0006 修复May 05, 2023 pm 04:01 PM

.NETFramework4是开发人员和最终用户在Windows上运行最新版本的应用程序所必需的。但是,在下载安装.NETFramework4时,许多用户抱怨安装程序在中途停止,显示以下错误消息-“ .NETFramework4hasnotbeeninstalledbecauseDownloadfailedwitherrorcode0x800c0006 ”。在您的设备上安装.NETFramework4时,如果您也在体验它,那么您就来对了地方

如何在 Windows 11/10 上使用 SetupDiag 识别 Windows 升级问题如何在 Windows 11/10 上使用 SetupDiag 识别 Windows 升级问题Apr 17, 2023 am 10:07 AM

每当您的Windows11或Windows10PC出现升级或更新问题时,您通常会看到一个错误代码,指示故障背后的实际原因。但是,有时,升级或更新失败可能不会显示错误代码,这时就会出现混淆。有了方便的错误代码,您就可以确切地知道问题出在哪里,因此您可以尝试修复。但是由于没有出现错误代码,因此识别问题并解决它变得极具挑战性。这会占用您大量时间来简单地找出错误背后的原因。在这种情况下,您可以尝试使用Microsoft提供的名为SetupDiag的专用工具,该工具可帮助您轻松识别错误背后的真

SCNotification 已停止工作 [修复它的 5 个步骤]SCNotification 已停止工作 [修复它的 5 个步骤]May 17, 2023 pm 09:35 PM

作为Windows用户,您很可能会在每次启动计算机时遇到SCNotification已停止工作错误。SCNotification.exe是一个微软系统通知文件,由于权限错误和点网故障等原因,每次启动PC时都会崩溃。此错误也以其问题事件名称而闻名。因此,您可能不会将其视为SCNotification已停止工作,而是将其视为错误clr20r3。在本文中,我们将探讨您需要采取的所有步骤来修复SCNotification已停止工作,以免它再次困扰您。什么是SCNotification.e

Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Apr 17, 2023 pm 02:25 PM

已安装Microsoft.NET版本4.5.2、4.6或4.6.1的MicrosoftWindows用户如果希望Microsoft将来通过产品更新支持该框架,则必须安装较新版本的Microsoft框架。据微软称,这三个框架都将在2022年4月26日停止支持。支持日期结束后,产品将不会收到“安全修复或技术支持”。大多数家庭设备通过Windows更新保持最新。这些设备已经安装了较新版本的框架,例如.NETFramework4.8。未自动更新的设备可能

适用于 Windows 11 的KB5012643破坏了.NET Framework 3.5应用程序适用于 Windows 11 的KB5012643破坏了.NET Framework 3.5应用程序May 09, 2023 pm 01:07 PM

自我们谈论影响安装KB5012643forWindows11的用户的新安全模式错误以来已经过去了一周。这个讨厌的问题并没有出现在微软在发布当天发布的已知问题列表中,因此让所有人都感到意外。好吧,就在您认为情况不会变得更糟的时候,微软为安装此累积更新的用户投下了另一颗炸弹。Windows11Build22000.652导致更多问题因此,这家科技公司警告Windows11用户,他们在启动和使用某些.NETFramework3.5应用程序时可能会遇到问题。听起来很熟悉?不过请不要惊

如何在Zend框架中使用ACL(Access Control List)进行权限控制如何在Zend框架中使用ACL(Access Control List)进行权限控制Jul 29, 2023 am 09:24 AM

如何在Zend框架中使用ACL(AccessControlList)进行权限控制导言:在一个Web应用程序中,权限控制是至关重要的一项功能。它可以确保用户只能访问其有权访问的页面和功能,并防止未经授权的访问。Zend框架提供了一种方便的方法来实现权限控制,即使用ACL(AccessControlList)组件。本文将介绍如何在Zend框架中使用ACL

PHP实现框架:Zend Framework入门教程PHP实现框架:Zend Framework入门教程Jun 19, 2023 am 08:09 AM

PHP实现框架:ZendFramework入门教程ZendFramework是PHP开发的一种开源网站框架,目前由ZendTechnologies维护,ZendFramework采用了MVC设计模式,提供了一系列可重用的代码库,服务于实现Web2.0应用程序和Web服务。ZendFramework深受PHP开发者的欢迎和推崇,拥有广泛

酷冷至尊携手Framework推出创新迷你机箱套件,兼容笔记本主板酷冷至尊携手Framework推出创新迷你机箱套件,兼容笔记本主板Dec 15, 2023 pm 05:35 PM

12月9日消息,最近,酷冷至尊在台北电脑展上的一次展示活动中,展示了与笔记本模块化方案提供商framework合作的迷你机箱套件,这个套件的独特之处在于,它可以兼容并安装来自framework笔记本的主板。目前,这款产品已经开始在市场上销售,售价定为39美元,按当前汇率折合大约279元人民币。这款机箱套件的型号被命名为“frameWORKMAINBOARDCASE”。在设计方面,它体现了极致的紧凑与实用性,尺寸仅为297x133x15毫米。它的设计初衷是为了能够无缝接入framework笔记本的

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),