3

I am using Symfony 4 try to inject a parameter into an Doctrine Entity Listener

Konfiguration:

App\EventListener\MyListener:
    arguments:
        - "%kernel.cache_dir%"
    tags:
        - { name: doctrine.orm.entity_listener }

Annotation of Entity Class:

@ORM\EntityListeners({"App\EventListener\MyListener"})

Listener:

namespace App\Eventlistener;
use Doctrine\ORM\Event\LifecycleEventArgs;
class MyListener {

    private $cacheDirectory;

    public function __construct($cacheDirectory)
    {
        $this->cacheDirectory = $cacheDirectory;
    }

    public function postUpdate($entity, LifecycleEventArgs $args)
    {
        ...
    }
}

When updating the Entity i get the Exception: Too few arguments to function __construnt(). 0 passed in ...\vendor\doctrine\doctrine-bundle\Mapping\ContainerAwareEntityListenerResolver.php on line 76 and exactly 1 expected

I also tried setter injection, but the setter method seems never to be called.

(This is a simplified Demo - I actually will need to inject a service and use it in postUpdate)

Documentation: https://symfony.com/doc/master/bundles/DoctrineBundle/entity-listeners.html (but without DI)

UPDATE: I found this Answer but this is not working with symfony 4.

  • 2
    Comment out the EntityListener annotation. That is used when Doctrine runs standalone. Just tagging your listener will suffice when using the framework. And while not directly related to your question, using an EventSubscriber will eliminate the need for the tag. – Cerad Jun 15 '18 at 12:27
  • @Cerad Thanks for your answer, but I do not want a Listener/Subscriber to be called when updating no matter what entity. I need an *Entity*EventListener - how should Symfony/Doctrine know which entity without this annotation? – Thomas Baumgartner Jun 18 '18 at 08:47
  • According to the docs the annotation is only need for older versions of Doctrine. I don't see any evidence that you can make an entity specific listener. Nothing I could find in the Doctrine docs. Do you have a link? – Cerad Jun 18 '18 at 11:44

0 Answers0