Another Doctrine2 Post. This time we’re taking a look on Event Listeners/Subscribers.
Event Listeners are a real powerful thing in Doctrine2. Besides LifeCycleCallbacks they can be used if you’ll want to scan through your Entity i.e. for specialized standard field. Also implementing a global Versionable behaviour (since that is no longer a native Doctrine behaviour) ist very easy to do inside Event Listeners.
My motivation for this quick blog post is just to give people a gist how to use EventListeners because the documentation is -again- a pain in the ass.
Im just using onFlush() here, since preUpdate() is somehow not called by SonataDoctrineORMAdminBundle which i’m using to mainly manage my Entities.
Lets start by creating a EventListener in My/Bundle/Listener/MyEventListener.php
Now all that is left to do is to attach the Event Listener to DI. If you’re using Symfony2 you’ll just need to update your app/config/config.yml
For further information feel free to take a look at the beautiful Doctrine2 Documentation, which I obviously love so much.