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条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路