3

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 Answer 1

5

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');
}
Sign up to request clarification or add additional context in comments.

2 Comments

is there a similar way to accomplish this with JMSSerializerBundle? I'm checking the code and unfortunately this seems to be out of chance
unfortunately there is no interface to specify priorities when using $em->getConnection()->getEventManager()->addEventListener(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.