我设置了一个侦听器类,在该类中,我将在任何主义的prePersist上设置ownerid列。我的services.yml文件看起来像这样…
services: my.listener: class: App\SharedBundle\Listener\EntityListener arguments: ["@security.context"] tags: - { name: doctrine.event_listener, event: prePersist }
我的班级看起来像这样…
use Doctrine\ORM\Event\LifecycleEventArgs; use Symfony\Component\Security\Core\SecurityContextInterface; class EntityListener { protected $securityContext; public function __construct(SecurityContextInterface $securityContext) { $this->securityContext = $securityContext; } /** * * @param LifecycleEventArgs $args */ public function prePersist(LifecycleEventArgs $args) { $entity = $args->getEntity(); $entityManager = $args->getEntityManager(); $entity->setCreatedby(); } }
其结果是以下错误。
ServiceCircularReferenceException:检测到服务“ doctrine.orm.default_entity_manager”的循环引用,路径:“ doctrine.orm.default_entity_manager-> doctrine.dbal.default_connection-> my.listener-> security.context-> security.authentication.manager-> fos_user .user_manager”。
我的假设是安全上下文已经注入到链中的某个位置,但是我不知道如何访问它。有任何想法吗?
我遇到了类似的问题,唯一的解决方法是将整个容器传递给构造函数(arguments: ['@service_container'])。
arguments: ['@service_container']
use Doctrine\ORM\Event\LifecycleEventArgs; use Symfony\Component\DependencyInjection\ContainerInterface; class MyListener { protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } // ... public function prePersist(LifeCycleEventArgs $args) { $securityContext = $this->container->get('security.context'); // ... } }