Search code examples
symfonydoctrine-ormdoctrinedoctrine-query

Same Doctrine ORM listener for multiple entitites


So I will be quick. Let's say you have a postPersist event. Can you make the same listener class respond to two different entities if they extend same interface?

        <service id="app.entity.my_listener"
                 class="App\Entity\MyListener" lazy="true">
            <tag name="doctrine.orm.entity_listener" entity="App\Entity\Entity1" event="postPersist"/>
            <tag name="doctrine.orm.entity_listener" entity="App\Entity\Entity2" event="postPersist"/>
            <tag name="kernel.event_subscriber" />
        </service>

Keep in mind, both entities extend the same EntityInterface so my function signature takes:

    public function postPersist(EntityInterface $entity, LifecycleEventArgs $event = null)

For "reasons" I can not validate this myself, but wondered if someone else is able to give an answer?


Solution

  • If you use doctrine lifecycle listener : https://symfony.com/doc/current/doctrine/events.html#doctrine-lifecycle-listeners

    You can make your case work. Since in this case they do not trigger on a specific entity. It is on your hand.
    So if the listener should respond to only a specific interface.
    As @Bossman said in his comment, you can do :

     public function postPersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
    
        // if this listener only applies to certain entity types,
        // add some code to check the entity type as early as possible
        if (!$entity instanceof EntityInterface) {
            return;
        }
    
        $entityManager = $args->getObjectManager();
        // ... do something with the Product entity
    }