首頁 > 後端開發 > php教程 > Zend Framework動作助理的用法解析

Zend Framework動作助理的用法解析

不言
發布: 2023-04-01 09:20:02
原創
1438 人瀏覽過

這篇文章主要介紹了Zend Framework動作助手(Zend_Controller_Action_Helper)用法,詳細分析了動作助手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##php
│  │  AjaxContext.php##php
.php
│  │  Cache.php
#│  │  ContextSwitch.php
│  │  FlashMessenger.php
│  │  Json.php##│php#│  .
│  │  ViewRenderer.php
#│  │
│  └─AutoComplete
│         
#常見的動作助手有


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 &#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);
  }
}
登入後複製

助理經紀人的常見用法:

一、註冊一個助手

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(&#39;My_Action_Helpers&#39;);
登入後複製

3.使用addPath()方法第一個參數為一個目錄,第二個為類別前綴(預設為'Zend_Controller_Action_Helper')。

用來將自己的類別前綴對應到指定的目錄。

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

二、判讀助手是否存在

使用hasHelper($name)方法來判定助理經紀人中是否存在某助手,$name是助手的短名稱(去掉前綴的):

// 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;;
}
登入後複製

從助手經紀人中取得助手有兩個靜態方法: getExistingHelper() 和getStaticHelper() 。 getExistingHelper()將取得助手僅當它先前被呼叫過或顯性地透過助手經紀人註冊過,否則就拋出一個例外。 getStaticHelper() 的做法和getExistingHelper()一樣,但如果還沒有註冊助手堆疊,它將嘗試初始化助手,為獲取你要配置的的助手,getStaticHelper()是一個好的選擇。

兩個方法都帶一個參數,$name,它是助手的短名稱(去掉前綴)。

// 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;);
}
登入後複製

#三、removeHelper($name)刪除助手經紀人中的某個助手,$name是助手的短名稱

// 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组件的用法解析

以上是Zend Framework動作助理的用法解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板