Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - listeners on doctrine / orm

Tags:

symfony

What is the best way to have an event that fires after a record is inserted in Symfony2 / Doctrine?

like image 886
user761540 Avatar asked Dec 21 '22 13:12

user761540


1 Answers

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)/

like image 176
Derek Stobbe Avatar answered Dec 26 '22 16:12

Derek Stobbe