将SecurityContext注入侦听器prepersist或preUpdate在Symfony2中获取用户在一个createdBy或updatedBy导致循环引用错误 [英] Injecting SecurityContext into a Listener prePersist or preUpdate in Symfony2 to get User in a createdBy or updatedBy Causes Circular Reference Error
问题描述
我设置了一个侦听器类,我将在任何教条prePersist上设置ownerid列。我的services.yml文件看起来像这样...
I setup a listener class where i'll set the ownerid column on any doctrine prePersist. My services.yml file looks like this ...
services:
my.listener:
class: App\SharedBundle\Listener\EntityListener
arguments: ["@security.context"]
tags:
- { name: doctrine.event_listener, event: prePersist }
,我的课程看起来像这样...
and my class looks like this ...
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。
ServiceCircularReferenceException: Circular reference detected for service "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> my.listener -> security.context -> security.authentication.manager -> fos_user.user_manager".
我的假设安全上下文已经注入到链中的某个地方,但我不知道如何访问它。有任何想法吗?
My assumption is that the security context has already been injected somewhere in the chain but I don't know how to access it. Any ideas?
推荐答案
我有类似的问题,唯一的解决方法是将整个容器传递给构造函数( arguments :['@service_container']
)。
I had similar problems and the only workaround was to pass the whole container in the constructor (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');
// ...
}
}
这篇关于将SecurityContext注入侦听器prepersist或preUpdate在Symfony2中获取用户在一个createdBy或updatedBy导致循环引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!