Tony Bogdanov Tony Bogdanov - 6 months ago 24
PHP Question

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.

Answer

is it possible to tell Symfony to listen for prePersist events for a particular Entity and then pass it to my listener?

No, it's not possible. Your listener will fire for every entity that is persisted. It's up to you to do an instanceof check in the event listener to ensure that your code only runs for a specific entity.