首页 文章

使用Symfony 2事件调度程序

提问于
浏览
13

如果有的话,Symfony 2捆绑开发人员应该如何使用Symfony 2系统库存的事件调度程序?

我一直在寻找Symfony事件调度员的来源,我看到的一些内容让我有点困惑,我是第三方捆绑创建者应该如何使用Symfony附带的事件调度程序 .

具体来说,我注意到一个股票Symfony系统有 two 事件调度程序服务 . event_dispatcherdebug.event_dispatcher . HttpKernel 使用哪种服务取决于环境,并由生成的dev或prod容器文件驱动 .

//dev kernel instantiation uses `debug.event_dispatcher` service
new \Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel(
            $this->get('debug.event_dispatcher'), 
            $this, 
            $this->get('debug.controller_resolver')
        );

//prod kernel instantiation uses `event_dispatcher` service         
new \Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel(
            $this->get('event_dispatcher'), 
            $this, 
            new \Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver($this, $this->get('controller_name_converter'), $this->get('monolog.logger.request', ContainerInterface::NULL_ON_INVALID_REFERENCE)));

到目前为止,这一切都是有道理的 - 因为它是 debug.event_dispatcher 在Web配置文件's event's选项卡中实现功能,包括查看调用哪些侦听器以及未调用哪些侦听器的功能 .

但是,我注意到大多数(如果不是全部)第三方捆绑包使用硬编码 event_dispatcher 服务调用 . 例如,JMS/JobQueueBundle使用以下内容

$this->dispatcher = $this->getContainer()->get('event_dispatcher');

像这样派生的事件正确地发送, but 不清楚捆绑作者如何避免这种情况,因为它们没有生成容器文件的优势 and HTTP内核对象不公开受保护的访问者调度程序对象 .

那么,这是Symfony中的一个错误吗?

或者 event_dispatcher 服务仅用于内核事件,这意味着所有这些捆绑作者都在滥用它?

或者(最有可能的候选人),是否是我遗漏或未考虑的其他事情?

1 回答

  • 7

    看起来我上面描述的场景不适用于最新版本的Symfony( 2.4.1 ) . 具体来说,在 2.4.1 中,生成的应用容器文件

    app/cache/dev/appDevDebugProjectContainer.php
    

    包含以下内容

    $this->aliases = array(
        //...
        'event_dispatcher' => 'debug.event_dispatcher',
        //...
    );
    

    也就是说,与我正在研究的Symfony 2.3.6 项目不同, event_dispatcher 服务已被别名化为 debug.event_dispatcher 服务(当Symfony在开发模式下运行时) . 这意味着当其他捆绑包在开发模式下请求 event_dispatcher 服务时,他们真的得到了 debug.event_dispatcher 服务 . 这使 debug.event_dispatcher 了解所有事件,并且可以正确地报告调度了哪些事件 .

    虽然它有意为Bundle开发人员使用 event_dispatch 服务来处理他们自己的事件 .

相关问题