在运行时更改订阅的事件 (Symfony/Doctrine ED)
Change subscribed events during runtime (Symfony/Doctrine ED)
以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],
],
];
}
}
假设此列表可以在运行时更改是否正确?
例如
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],
],
]
}
}
当我在运行时设置 $someToggle
时,这是否合法并取消订阅 logException
和 notifyException
?
不,您不能通过向 getSubscribedEvents():array
方法添加逻辑来动态更改订阅者监听的事件。
该方法 运行 仅在构建容器时的编译器传递期间,因此只会在清除缓存后执行。
在 运行 时尝试更改此设置将无效。
这样做的实际方法是将此逻辑放入 listener/subscriber 的“工作”部分:
public function processException(ExceptionEvent $event)
{
if (!$this->shouldProcessException()) {
return;
}
}
除非获取 shouldProcessException()
的值非常昂贵,否则对性能的影响将非常小或可以忽略不计。
以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],
],
];
}
}
假设此列表可以在运行时更改是否正确?
例如
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],
],
]
}
}
当我在运行时设置 $someToggle
时,这是否合法并取消订阅 logException
和 notifyException
?
不,您不能通过向 getSubscribedEvents():array
方法添加逻辑来动态更改订阅者监听的事件。
该方法 运行 仅在构建容器时的编译器传递期间,因此只会在清除缓存后执行。
在 运行 时尝试更改此设置将无效。
这样做的实际方法是将此逻辑放入 listener/subscriber 的“工作”部分:
public function processException(ExceptionEvent $event)
{
if (!$this->shouldProcessException()) {
return;
}
}
除非获取 shouldProcessException()
的值非常昂贵,否则对性能的影响将非常小或可以忽略不计。