doctrine PostPersist & PostUpdate in one listener doctrine PostPersist & PostUpdate in one listener symfony symfony

doctrine PostPersist & PostUpdate in one listener


One way to avoid a recursive loop with doctrine listeners is to have the listener remove itself from the event manager before doing any updating/persisting.

So for example in some code I've worked on I have something like this:

// $evm is the Event Manager grabbed from the Entity Manager that// is part of the Event passed to the listener functionpublic function removeThyself($evm){    $evm->removeEventListener(Events::postFlush, $this);    $evm->removeEventListener(Events::onFlush, $this);}public function readdTheyself($evm){    $evm->addEventListener(Events::postFlush, $this);    $evm->addEventListener(Events::onFlush, $this);}

Where these functions remove the event listener from any events the listener is registered on.

Then before doing anything from the listener that affects the database I call these to make sure the event listener does not get called. e.g.

// $em is the Entity Manager, $evm is the Event Manager$this->removeThyself($evm);$em->flush($toFlush);$this->readdTheyself($evm);