简体   繁体   中英

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.

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 }

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM