DEV Community

Julian
Julian

Posted on

Doctrine simple event listener are not Interface compatible

the old way of defining event listener for doctine was like this:

service.yaml:

C33s\Doctrine\Listener\Entity\InjectFeatureManagerListener:
    tags:
        - { name: doctrine.event_listener, event: postLoad, connection: default, priority: 0 }
Enter fullscreen mode Exit fullscreen mode

where the listener look like that:

class InjectFeatureManagerListener
{
    /**
     * @var FeatureManagerInterface
     */
    protected $featureManager;

    /**
     * @param FeatureManagerInterface $featureManager
     *
     */
    public function __construct(FeatureManagerInterface $featureManager)
    {
        $this->featureManager = $featureManager;
    }

    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof FeatureFlagable) {
            $entity->setFeatureFlagManager($this->featureManager);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

btw. don't do that. don't inject stuff into your entity. its a bad practice.

this way the listener is called for each entity and each entity is checked against the FeatureFlagable interface. so i have the nice feature of injecting the feature manager in each entity which implements the FeatureFlagable interface no matter which entity it is.

with the new way to define the listener https://symfony.com/blog/new-in-symfony-4-4-simpler-event-listeners its getting shorter but is incompatible with interfaces:

the following config will not work because no entity with the name FeatureFlagable exists.

service.yaml

C33s\Doctrine\Listener\Entity\InjectFeatureManagerListener:
    tags:
        - { name: doctrine.orm.entity_listener, event: postLoad, entity: C33s\Doctrine\Entity\Interfaces\FeatureFlagable, connection: default, priority: 0, lazy: true }

Enter fullscreen mode Exit fullscreen mode

changing the code by adding the explicit entity name App\Entity\News

...
        - { name: doctrine.orm.entity_listener, event: postLoad, entity: App\Entity\News, connection: default, priority: 0, lazy: true }
...
Enter fullscreen mode Exit fullscreen mode

make it work again but i would need to tag all my entities manually even if they are already "marked"/"tagged" with the FeatureFlagable interface.

i haven't digged too deep into the doctrine event listener code just came to vendor/doctrine/doctrine-bundle/DependencyInjection/Compiler/EntityListenerPass.php. maybe its an easyfix. would be nice to be able to use interfaces again.

Top comments (0)