Symfony2 add event listener dynamically

2019-05-16 10:18发布

问题:

How would you add an event listener (in my case it's a doctrine event) dynamically to the kernel without using services.yml pattern?

回答1:

I found the answer myself after doing some digging into the vendor directory and appProdProjectContainer.php file. If you want your events to be registered with event manager you have to specify the tags in your services.yml for the events that you want this to trigger for like:

  event_listener:
      class: Company\MyBundle\Listener\MyListener
      arguments: [@security.context, @logger]
      tags:
          -   
              name: doctrine.event_listener
              event: preRemove
          -   
              name: doctrine.event_listener
              event: onFlush

Now if you want to dynamically register these events, you need to leave the event_listener resource in services.yml, but delete the tags part and dynamically add them that as follow:

if (something) {
  $evm = $em->getConnection()->getEventManager();
  $evm->addEventListener(
      [
        0 => 'preRemove',
        1 => 'onFlush'
      ],
      $this->container->get('event_listener');
}