问题描述
是否可以设置事件监听器(或执行其他操作?)来监听 all ,由Symfony 2 AppKernel
应用程序针对特定请求触发的事件?
Is it possible to setup an event listener (or do — something else?) to listen for all the events fired by a Symfony 2 AppKernel
application for a particular request?
也就是说,我知道我可以使用 app_dev.php
浏览应用程序,并使用探查器查看所有 listeners 的列表,但我对此感兴趣获取已调度/触发的每个事件的列表.我知道某些事件系统具有特殊的全局/所有侦听器,这使我可以接收每个事件.我想知道Symfony是否具有类似的功能,或者是否存在另一种机制来获取特定页面上所有可用事件的列表.
That is, I know I can browse an application with app_dev.php
and use the profiler to view a list of all the listeners, but I'm interested in grabbing a list of every event that's been dispatched/fired. I know some event systems have a special global/all listener what would let me receive every event. I'm wondering if Symfony has something similar, or if there's another mechanism to get a list of all the available events on a particular page.
我还知道我可以向事件调度程序类之一添加一些临时调试代码
I also know I could add some temporary debugging code to one of the event dispatcher classes
Symfony/Component/EventDispatcher/EventDispatcher.php
Symfony/Component/HttpKernel/Debug/ContainerAwareTraceableEventDispatcher.php
Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php
但是我正在寻找的东西要少一点hack/破坏性较小.
but I'm looking for something that is less of a hack/less-destructive.
Symfony的新手,但编程新手.抱歉,如果这是一个幼稚的问题,但在Google上搜索并没有透露我所追求的.
New to Symfony, but not new to programming. Apologies if this is a naive question, but googling about hasn't revealed what I'm after.
推荐答案
干净的方法是创建自己的EventDispatcher,该EventDispatcher将执行日志记录或发生事件时要执行的任何操作.看看默认值了解其工作原理.
The clean way would be creating your own EventDispatcher which executes your logging or whatever you're trying to do if an event occurs. Have a look at the default one to get an idea of how it works.
现在首先创建课程
use Symfony\Component\EventDispatcher\EventDispatcher;
class MyDispatcher extends EventDispatcher
{
// sadly those properties aren't protected in EventDispatcher
private $listeners = array();
private $sorted = array();
public function dispatch($eventName, Event $event = null)
{
if (null === $event) {
$event = new Event();
}
$event->setDispatcher($this);
$event->setName($eventName);
// do something with the event here ... i.e. log it
if (!isset($this->listeners[$eventName])) {
return $event;
}
$this->doDispatch($this->getListeners($eventName), $eventName, $event);
return $event;
}
...然后将MyDispatcher注册为symfony的默认目录.
... then register your MyDispatcher as symfony's default one.
(通过覆盖原始的event_dispatcher服务)
( by overwriting the original event_dispatcher service )
app/config/config.yml
services:
event_dispatcher:
class: Vendor\YourBundle\MyDispatcher
arguments: [@service_container]
...甚至更简单,只需覆盖类参数.
... or even simpler just override the class parameter being used by symfony when creating the service.
parameters:
event_dispatcher.class: Vendor\YourBundle\MyDispatcher
这篇关于收听Symfony 2中的所有事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!