Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine in Symfony 2: Listening for events from a particular Entity

I have a Doctrine Entity (News) which I listen for the event prePersist. For that I use an event listener with the method prePersist.

My services.yml looks like this:

listener.entity.news:
    class: A\BBundle\Listeners\Entity\NewsListener
    tags:
        - { name: doctrine.event_listener, event: prePersist }

This is fine and everything works. But the documentation states that when a persist() is called, a prePersist event is spawned. Then as my config states NewsListener will catch it and execute some code. Inside the method where I catch the event I should check if the event comes from the News entity. Here is where I wonder, is it possible to tell Symfony to listen for prePersist events for a particular Entity and then pass it to my listener?

Currently (as I understand it), whenever doctrine spawns a prePersist event ALL listeners are notified. Isn't it better to say which listeners should listen which event spawners, even if that should be optional, rather than notifying all and letting them filter the ones they need?

I hope I asked my question correctly.

like image 517
Tony Bogdanov Avatar asked Feb 10 '12 17:02

Tony Bogdanov


1 Answers

This seems to be supported since Doctrine 2.4:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners

like image 170
thomaskonrad Avatar answered Oct 27 '22 01:10

thomaskonrad