search
HomeBackend DevelopmentPHP TutorialZend Framework创建自己的动作助手详解_php实例

本文实例讲述了Zend Framework创建自己的动作助手实现方法。分享给大家供大家参考,具体如下:

助手的抽象基类是Zend_Controller_Action_Helper_Abstract,如要定义自己的助手,需要继承此类

类的源代码如下:

<&#63;php
/**
 * @see Zend_Controller_Action
 */
require_once 'Zend/Controller/Action.php';
abstract class Zend_Controller_Action_Helper_Abstract
{
  /**
   * $_actionController
   *
   * @var Zend_Controller_Action $_actionController
   */
  protected $_actionController = null;
  /**
   * @var mixed $_frontController
   */
  protected $_frontController = null;
  /**
   * setActionController()
   *
   * @param Zend_Controller_Action $actionController
   * @return Zend_Controller_ActionHelper_Abstract Provides a fluent interface
   */
  public function setActionController(Zend_Controller_Action $actionController = null)
  {
    $this->_actionController = $actionController;
    return $this;
  }
  /**
   * Retrieve current action controller
   *
   * @return Zend_Controller_Action
   */
  public function getActionController()
  {
    return $this->_actionController;
  }
  /**
   * Retrieve front controller instance
   *
   * @return Zend_Controller_Front
   */
  public function getFrontController()
  {
    return Zend_Controller_Front::getInstance();
  }
  /**
   * Hook into action controller initialization
   *
   * @return void
   */
  public function init()
  {
  }
  /**
   * Hook into action controller preDispatch() workflow
   *
   * @return void
   */
  public function preDispatch()
  {
  }
  /**
   * Hook into action controller postDispatch() workflow
   *
   * @return void
   */
  public function postDispatch()
  {
  }
  /**
   * getRequest() -
   *
   * @return Zend_Controller_Request_Abstract $request
   */
  public function getRequest()
  {
    $controller = $this->getActionController();
    if (null === $controller) {
      $controller = $this->getFrontController();
    }
    return $controller->getRequest();
  }
  /**
   * getResponse() -
   *
   * @return Zend_Controller_Response_Abstract $response
   */
  public function getResponse()
  {
    $controller = $this->getActionController();
    if (null === $controller) {
      $controller = $this->getFrontController();
    }
    return $controller->getResponse();
  }
  /**
   * getName()
   *
   * @return string
   */
  public function getName()
  {
    $fullClassName = get_class($this);
    if (strpos($fullClassName, '_') !== false) {
      $helperName = strrchr($fullClassName, '_');
      return ltrim($helperName, '_');
    } elseif (strpos($fullClassName, '\\') !== false) {
      $helperName = strrchr($fullClassName, '\\');
      return ltrim($helperName, '\\');
    } else {
      return $fullClassName;
    }
  }
}

助手基类提供的常用方法如下:

setActionController() 用来设置当前的动作控制器。
init(),该方法在实例化时由助手经纪人触发,可用来触发助手的初始化过程;
动作链中多个控制器使用相同的助手时,如要恢复状态时将十分有用。
preDispatch()分发动作之前触发。
postDispatch()分发过程结束时触发——即使preDispatch()插件已经跳过了该动作。清理时大量使用。
getRequest() 获取当前的请求对象。
getResponse() 获取当前的响应对象。
getName() 获取助手名。获取了下划线后面的类名部分,没有下划线则获取类的全名。

例如,如果类名为Zend_Controller_Action_Helper_Redirector,他将返回 Redirector,如果类名为FooMessage,将会返回全名。

举例说明自定义动作助手类

作用:解析传入的网址,返回各个部分。使用parse_url解析指定的网址。
用zendstudio新建一个zend framework项目helper_demo1。

新增文件:/helper_demo1/library/Application/Controller/Action/Helpers/UrlParser.php

<&#63;php
require_once 'Zend/Controller/Action/Helper/Abstract.php';
class Application_Controller_Action_Helpers_UrlParser extends Zend_Controller_Action_Helper_Abstract
{
  public function __construct()
  {
  }
  /**
   * Parse url
   *
   * @param String $url
   * @return Array part of url
   */
  public function parse($url)
  {
    return parse_url($url);
  }
}

修改文件:/helper_demo1/application/Bootstrap.php

<&#63;php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  protected function _initAutoload()
  {
    $autoloader = Zend_Loader_Autoloader::getInstance();
    $autoloader->registerNamespace(array('Application_'));
  }
  protected function _initActionHelpers() {
    //用前缀形式
    //Zend_Controller_Action_HelperBroker::addPrefix('Application_Controller_Action_Helpers');
    //指定目录和前缀
    //Zend_Controller_Action_HelperBroker::addPath('/www/helper_demo1/library/Application/Controller/Action/Helpers',
    //                  'Application_Controller_Action_Helpers');
    //new一个助手类传入
    Zend_Controller_Action_HelperBroker::addHelper(new Application_Controller_Action_Helpers_UrlParser);
  }
}

修改测试action:/helper_demo1/application/controllers/IndexController.php

<&#63;php
class IndexController extends Zend_Controller_Action
{
  public function init()
  {
    /* Initialize action controller here */
  }
  public function indexAction()
  {
    $urlParser = $this->_helper->getHelper('UrlParser');
  var_dump($urlParser->parse('http://www.php.net/article/80479.htm'));
  }
}

以上介绍了自定义动作助手类,以及简单的使用方法。

需要注意的就是什么是助手类的前缀,助手类的名称以及助手的路径。

更多关于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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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 Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools