duanjue9889 2014-06-28 17:42
浏览 19
已采纳

调度控制器zf2事件管理器

I have a base controller named MyController I extend my Controller from MyController instead of AbstractActionController What's wrong with this code ?
It doesn't work :

$sharedEventManager->attach('MyController', 'dispatch', function ($e) {
    $controller = $e->getTarget();
},100) ;

but this does :

$sharedEventManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function ($e) {
    $controller = $e->getTarget();
},100) ;
  • 写回答

2条回答 默认 最新

  • dongsheng9203 2014-06-29 11:30
    关注

    The first parameter of the SharedEventManager::attach() is the identity of the event manager to target. This identity is dynamically assigned for any class that is event capable (implements Zend\EventManager\EventManagerAwareInterface) or has otherwise had it's identity set via $eventManager->setIdentity().

    The question refers to the \Zend\Mvc\Controller\AbstractActionController; this itself is an identity given to any controller that extends \Zend\Mvc\AbstractActionController (among others), allowing for just one id to attach() to target all controllers.

    To target just one controller (which is perfectly valid, there are many use cases), you can do so in two ways:

    1. via the SharedEventManager, external to the controller class (as you have been doing)
    2. directly fetching said controller's event manager and handling the events within the controller class.

    via SharedEventManager

    Use the fully qualified class name as this is is added as an identity to the event manager

    $sharedEventManager->attach(
        'MyModule\Controller\FooController', 'dispatch', function($e){
        // do some work
    });
    

    Within controller

    I modify the normal attachDefaultListeners() method (which is called automatically), this is where you can attach events directly.

    namespace MyModule\Controller;
    
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\EventManager\EventInterface;
    
    class FooController extends AbstractActionController
    { 
        protected function attachDefaultListeners()
        {
          // make sure you attach the defaults!
          parent::attachDefaultListeners();
    
          // Now add your own listeners
          $this->getEventManager()->attach('dispatch', array($this, 'doSomeWork'));
        }
    
        public function doSomeWork(EventInterface $event) {
          // do some work
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决