在运行时更改订阅的事件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',]
    }
}

当我在运行时设置 logException 时,这是否合法并取消订阅 notifyException$sometoggle

解决方法

不,您不能通过向 getSubscribedEvents():array 方法添加逻辑来动态更改订阅者监听的事件。

该方法仅在构建容器的编译器传递期间运行,因此只有在清除缓存后才会执行。

尝试在运行时更改此设置无效。

这样做的实际方法是将此逻辑放入侦听器/订阅者的“工作”部分:

public function processException(ExceptionEvent $event)
{

    if (!$this->shouldProcessException()) {
        return;
    }
}

性能影响将非常小或可以忽略不计,除非获得 shouldProcessException() 的值的成本很高。