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.
Since the Doctrine 2.0 Documentation for this seems to be kinda fucked up at the moment, here is a working exampe of a One-To-Many, Unidirectional with Join-Table Association Mapping
Scenario
A driver can have many documents, but a document has no direct Entity relation to a driver.
Solution
Use Many-To-Many to encode it properly.
Im using annotations with the ORM-Namespace since its embedded in Symfony2.
Note that One-To-Many is coded throughout Many-To-Many but the unique index is set for the join table.
In my POV thats kinda confusing since there is a @One-To-Many relationship, but whatever!