Your Location is: Home > Php

How to create a new entity when another entity is created/updated/changed with Doctrine?

From: Philippines View: 4781 Wolfone 

Question

I am working on a Symfony (5.1) application using Doctrine 2.7.

I want to create logging-Entities for another entity that I have. I got some Change-Entity and for each change in my original entities I want to create a new Change-Entity instance, and persist it.

I thought I might use doctrine's prePersist, postUpdate annotations and do on basically doing something like this:

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class OriginalEntity
{
    /**
     * @ORM\PrePersist
     */
    public function onCreate(LifecycleEventArgs $args)
    {
        $em = $args->getEntityManager();
        //...create a Change entity with some Information and persist it...
    }
}

But it has been stated in multiple questions here on SO that it is bad practice to use the entity manager inside entity-classes.

How can this be done without injecting the Entity Manager in the entity class?

Best answer

Have you looked into dispatching / listening to events ? I don't have the code in my head but I'm thinking of something like this :

  • make a listener class to consume events triggered on prePersist and postUpdate. This class has access to the entity manager

  • onCreate method is triggered on entity and dispatch an onCreate event, the listener get notified and perform the action

This page should guide you as to which type of listener / subscriber would be the best fit for your case https://symfony.com/doc/current/doctrine/events.html