在运行时更改订阅的事件(Symfony/Doctrine ED) [英] Change subscribed events during runtime (Symfony/Doctrine ED)
问题描述
以 https://symfony.com/doc/current/event_dispatcher.html 为例
class ExceptionSubscriber 实现 EventSubscriberInterface{公共静态函数 getSubscribedEvents(){//返回订阅的事件,它们的方法和优先级返回 [KernelEvents::EXCEPTION =>[['processException', 10],['logException', 0],['notifyException', -10],],];}}
假设可以在运行时更改此列表是否正确?
例如
class ExceptionSubscriber 实现 EventSubscriberInterface{受保护的 $someToggle = false;公共静态函数 getSubscribedEvents(){如果 ($this->someToggle) {返回 [KernelEvents::EXCEPTION =>['processException']]}返回 [KernelEvents::EXCEPTION =>[['processException', 10],['logException', 0],['notifyException', -10],],]}}
当我在运行时设置 $someToggle
时,这是否合法并取消订阅 logException
和 notifyException
?
不,您不能通过向 getSubscribedEvents():array
方法添加逻辑来动态更改订阅者侦听的事件.>
该方法仅在构建容器的编译器传递期间运行,因此只有在清除缓存后才会执行.
尝试在运行时更改此设置无效.
这样做的实际方法是将此逻辑放入工作"中.听众/订阅者的一部分:
公共函数processException(ExceptionEvent $event){if (!$this->shouldProcessException()) {返回;}}
性能影响将非常小或可以忽略不计,除非获取 shouldProcessException()
的值会很昂贵.
Taking the example from https://symfony.com/doc/current/event_dispatcher.html
class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::EXCEPTION => [
['processException', 10],
['logException', 0],
['notifyException', -10],
],
];
}
}
Is it correct to assume that this list can be changed during runtime?
E.g.
class ExceptionSubscriber implements EventSubscriberInterface
{
protected $someToggle = false;
public static function getSubscribedEvents()
{
if ($this->someToggle) {
return [KernelEvents::EXCEPTION => ['processException']]
}
return [
KernelEvents::EXCEPTION => [
['processException', 10],
['logException', 0],
['notifyException', -10],
],
]
}
}
Is this legit and unsubscribes logException
and notifyException
when I set $someToggle
during runtime?
No, you cannot change dynamically what events a subscriber listen to by adding logic to the getSubscribedEvents():array
method.
That method is run only during a compiler pass when the container is being built, so it will only be executed after cache is cleared.
Trying to change this at runtime will have no effect.
The practical way of doing this is to put this logic into the "work" part of the listener/subscriber:
public function processException(ExceptionEvent $event)
{
if (!$this->shouldProcessException()) {
return;
}
}
The performance hit would be very small or negligible, unless getting the value for shouldProcessException()
was otherwise expensive.
这篇关于在运行时更改订阅的事件(Symfony/Doctrine ED)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!