将 SecurityContext 注入 Symfony2 中的侦听器 prePersist 或 preUpdate 以在 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: AppSharedBundleListenerEntityListener
arguments: ["@security.context"]
tags:
- { name: doctrine.event_listener, event: prePersist }
我的班级看起来像这样......
and my class looks like this ...
use DoctrineORMEventLifecycleEventArgs;
use SymfonyComponentSecurityCoreSecurityContextInterface;
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();
}
}
这样做的结果是以下错误.
The result of this is the following error.
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?
推荐答案
我遇到了类似的问题,唯一的解决方法是在构造函数中传递整个容器(参数:['@service_container']
).
I had similar problems and the only workaround was to pass the whole container in the constructor (arguments: ['@service_container']
).
use DoctrineORMEventLifecycleEventArgs;
use SymfonyComponentDependencyInjectionContainerInterface;
class MyListener
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
// ...
public function prePersist(LifeCycleEventArgs $args)
{
$securityContext = $this->container->get('security.context');
// ...
}
}
这篇关于将 SecurityContext 注入 Symfony2 中的侦听器 prePersist 或 preUpdate 以在 createdBy 或 updatedBy 中获取用户导致循环引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!