欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Zend Framework动作助手(Zend_Controller_Action_Helper)用法详解

程序员文章站 2024-04-01 19:56:34
本文实例讲述了zend framework动作助手(zend_controller_action_helper)用法。分享给大家供大家参考,具体如下: 通过助手模式,可以...

本文实例讲述了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的实现以及常用方法列表

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

助手经纪人的常见用法:

一、注册一个助手

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