What is the best way to have an event that fires after a record is inserted in Symfony2 / Doctrine?
First, register a service as a Doctrine event listener:
app/config.yml
:
services:
foo.listener:
class: Vendor\FooBundle\BarClass
tags:
- { name: doctrine.event_listener, event: postPersist, method: onPostPersist }
Then in your listener class, define an onPostPersist
method (or whatever you named the method in the config) that takes a Doctrine\ORM\Event\LifecycleEventArgs
argument:
public function onPostPersist(LifecycleEventArgs $eventArgs)
{
// do stuff with the entity here
}
Note that you can't pass an instance of EntityManager to the listener class, because $eventArgs contains a reference to it, and doing so will throw a CircularReferenceException.
Doctrine Project documentation here. Symfony Project documentation here (out of date, but included for reference)/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With