问题描述
在我的包中,我想利用 kernel.terminate
事件来刷新一些关于 webservice api 调用的统计信息.然而,我没有找到任何资源来以最好的方式做到这一点.
In my bundle, I want to take advantage of the kernel.terminate
event to flush some statistics about webservice api call. Yet, I didn't find any resources to do it in the best way.
在监听器 GuzzleExceptionListener
(他的作用是拦截每个失败的 webservice 调用),我在其中注入了 EntityManger
服务.:
On a listener GuzzleExceptionListener
(his role is to intercept every fail webservice call) in which i've injected the EntityManger
service. :
if ($exception instanceof BadResponseException) {
$entityManager = $this->entityManager;
$dispatcher = new EventDispatcher;
$dispatcher->addListener('kernel.terminate', function (Event $event) use ($entityManager) {
$repository = $entityManager->getRepository("somerepository");
// do some treatment for stats
$entityManager->persist($apicall);
$entityManager->flush();
});
}
GuzzleExceptionListener
的声明:
<service id="my_service" class="%my_class%">
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
<argument type="service" id="doctrine.orm.entity_manager" />
</service>
无论如何,当事件 kernel.terminate
被触发时,这个闭包不会被调用.为什么 ?是因为它本身就在侦听器中吗?
Anyhow, this closure is not called when the event kernel.terminate
is fired. Why ? Is it because it's inside a listener itself ?
推荐答案
你应该注入 symfony 配置的事件调度器服务 (@event_dispatcher
) 而不是在监听器中创建一个新的.
You should inject symfony's configured event dispatcher service (@event_dispatcher
) instead of creating a new one inside the listener.
如果你只创建它并添加一个事件监听器 symfony 仍然没有引用这个新创建的 EventDispatcher
对象,因此不会使用它.
If you only create it and add an event-listener symfony still has no reference to this newly created EventDispatcher
object and therefore won't use it.
<service id="my_service" class="%my_class%">
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
<argument type="service" id="doctrine.orm.entity_manager" />
<argument type="service" id="event_dispatcher" />
</service>
这篇关于如何在事件侦听器中利用 kernel.terminate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!