`
lfq618
  • 浏览: 85504 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

zend framework插件机制

阅读更多

ZF中的“插件”提供了对页面动作的扩展接口,只需实现Zend_Controller_Plugin_Abstract的相应方法。
文档中说道:

  1. routeStartup() 在 Zend_Controller_Front 向注册的Router发送请求前被调用。
  2. routeShutdown() 在Router完成请求的路由后被调用。
  3. dispatchLoopStartup() 在 Zend_Controller_Front 进入其分发循环(dispatch loop)前被调用。
  4. preDispatch() 在动作由Dispatcher分发前被调用。该回调方法允许代理或者过滤行为。通过修改请求和重设分发标志位(利用 Zend_Controller_Request_Abstract::setDispatched(false) )当前动作可以跳过或者被替换。
  5. postDispatch() 在动作由Dispatcher分发后被调用。该回调方法允许代理或者过滤行为。通过修改请求和重设分发标志位(利用 Zend_Controller_Request_Abstract::setDispatched(false) )可以指定新动作进行分发。
  6. dispatchLoopShutdown() 在 Zend_Controller_Front 推出其分发循环后调用。

代码中可以看到,Zend_Controller_Front在构造函数中初始化了Zend_Controller_Plugin_Broker(维护了 一个Plugin列表_plugins),之后在registerPlugin中把对应的Plugin加入到列表中,触发事件的时候会依次调用 _plugins列表中的Plugin调用响应的方法。

自定义的插件继承自Zend_Controller_Plugin_Abstract,然后使用Zend_Controller_Front的registerPlugin方法注册即可:

class MyPlugin extends Zend_Controller_Plugin_Abstract 
{
    
public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        
$this->getResponse()->appendBody("<p>routeStartup() called</p>"n");
    }

    
public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        
$this->getResponse()->appendBody("<p>routeShutdown() called</p>"n");
    }

    
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        
$this->getResponse()->appendBody("<p>dispatchLoopStartup() called</p>"n");
    }

    
public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        
$this->getResponse()->appendBody("<p>preDispatch() called</p>"n");
    }

    
public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        
$this->getResponse()->appendBody("<p>postDispatch() called</p>"n");
    }

    
public function dispatchLoopShutdown()
    {
        
$this->getResponse()->appendBody("<p>dispatchLoopShutdown() called</p>"n");
    }
}

Zend_Controller_Front
::getInstance()->registerPlugin(new MyPlugin());




错误处理(Zend_Controller_Plugin_ErrorHandler)

Zend_Controller_Plugin_ErrorHandler默认的Action为"error",Controller是"Error"。 所以自定义一个继承自Zend_Controller_Action的类ErrorController、实现errorAction方法、创建 error.phtml就可以让Zend_Controller_Plugin_ErrorHandler找到了。

若在Zend_Controller_Front::dispatch()前设置了'noErrorHandler'为true则不加载Zend_Controller_Plugin_ErrorHandler。
若设置了Zend_Controller_Front::throwExceptions(true)则出错时直接throw,不写到_response的$_exceptions列表中。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics