我正在使用Symfony 4尝试将参数注入Doctrine Entity Listener

Konfiguration:

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

实体类注释:

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

监听器:

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)
    {
        ...
    }
}

更新实体时,我得到异常:函数__construnt()的参数太少 . 0传递到第76行的... \ vendor \ doctrine \ doctrine-bundle \ Mapping \ ContainerAwareEntityListenerResolver.php并且正好是预期的1

我也尝试过setter注入,但似乎永远不会调用setter方法 .

(这是一个简化的演示 - 我实际上需要注入一个服务并在postUpdate中使用它)

文档:https://symfony.com/doc/master/bundles/DoctrineBundle/entity-listeners.html(但没有DI)

更新:我发现this Answer但这不适用于symfony 4 .