Search code examples
phpsymfonydoctrine

How can I add multiple events in services.yml file as event Listeners in Doctrine symfony


I am using this:

my.listener:
        class: Acme\SearchBundle\Listener\SearchIndexer
        tags:
            - { name: doctrine.event_listener, event: postPersist }

Now if I try to listen for two events like this:

- { name: doctrine.event_listener, event: postPersist, preUpdate }

it gives an error.


Solution

  • You need an event subscriber instead of an event listener.

    You'd change the service tag to doctrine.event_subscriber, and your class should implement Doctrine\Common\EventSubscriber. You need to define a getSubscribedEvents to satisfy EventSubscriber which returns an array of events you want to subscribe to.

    ex

    <?php
    
    namespace Company\YourBundle\Listener;
    
    use Doctrine\Common\EventArgs;
    use Doctrine\Common\EventSubscriber;
    
    class YourListener implements EventSubscriber
    {
        public function getSubscribedEvents()
        {
            return array('prePersist', 'onFlush');
        }
    
        public function prePersist(EventArgs $args)
        {
    
        }
    
        public function onFlush(EventArgs $args)
        {
    
        }
    }