Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Doctrine lifecycle events in my code

Question: how to trigger Doctrine lifecycle events in my code, having the entity data available?

Details

  • I have an active listener on the Doctrine postPersist and postUpdate events.
  • I cannot modify / override this listener.
  • In some places in my code, for performance reasons, I use DBAL to save data instead of ORM methods.
  • I'd like to stick to the same event system.

Thank you in advance for your help.

like image 501
Francesco Abeni Avatar asked Feb 07 '23 16:02

Francesco Abeni


2 Answers

Extending @Cerad answer, here's a very basic sample code to achieve the result (trigger a Doctrine LifeCycle event). This sample assumes we're in a Symfony controller:

use Doctrine\ORM\Event\LifecycleEventArgs;
// ...
$user = new AppBundle\Entity\User();
// ... do something with the user
$entityManager = $this->getDoctrine()->getManager();
$eventManager = $entityManager->getEventManager();
$eventArgs = new LifecycleEventArgs($user, $entityManager);
$eventManager->dispatchEvent(\Doctrine\ORM\Events::postPersist, $eventArgs);
like image 108
Francesco Abeni Avatar answered Feb 10 '23 07:02

Francesco Abeni


Assuming you have access to the entity manager then:

$eventManager = $entityManager->getEventManager();

After that you can build and dispatch events per the documentation.

I checked to see if there is a predefined service but did not see one. But you probably define one as a factory and inject it as needed.

Hope this is what you are asking for.

like image 20
Cerad Avatar answered Feb 10 '23 05:02

Cerad