Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 640
Mirage Avatar asked Jul 25 '12 04:07

Mirage


People also ask

Can you add multiple event listeners to an element?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

How do I add multiple events in addEventListener?

Unfortunately, you can't pass in multiple events to a single listener like you might in jQuery and other frameworks. For example, you cannot do this: document. addEventListener('click mouseover', function (event) { // do something... }, false);

What is event dispatcher in Symfony?

The EventDispatcher component provides tools that allow your application components to communicate with each other by dispatching events and listening to them.

Are Symfony events Async?

It allows to send events as MQ messages and process them async.


2 Answers

I think you can do like this:

my.listener:
        class: Acme\SearchBundle\Listener\SearchIndexer
        tags:
            - { name: doctrine.event_listener, event: postPersist }
            - { name: doctrine.event_listener, event: preUpdate }
like image 105
mask8 Avatar answered Oct 14 '22 06:10

mask8


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)
    {

    }
}
like image 31
Adrian Schneider Avatar answered Oct 14 '22 07:10

Adrian Schneider