Symfony2 - Learning trainees / orm

What is the best way to trigger an event after recording in Symfony2 / Doctrine?

+4
source share
2 answers

First register the 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 the onPostPersist method (or what you called the method in config) that takes the Doctrine\ORM\Event\LifecycleEventArgs argument:

 public function onPostPersist(LifecycleEventArgs $eventArgs) { // do stuff with the entity here } 

Note that you cannot pass an EntityManager instance to the listener class, because $ eventArgs contains a reference to it, and a CircularReferenceException is thrown.

Doctrine project documentation here . Symfony documentation here (deprecated but included for reference) /

+10
source

Try entering the container itself instead of the security context. with FOS_USER, security.context depends on your listener (EM), and your listener requires security.context.

 <service id="foo.listener" class="%foo.listener.class%"> <argument type="service" id="service_container"/> <tag name="doctrine.event_listener" event="postPersist" method="fooMethod" /> </service> 

By the way, at least in XML, the method name does not seem to work, by default it calls the postPersist method and ignores any method name you give (fooMethod); Please let me know if this is the case with the YAML configuration either, or I'm just wrong.

+1
source

All Articles