Jie*_*eng 12 dependency-injection symfony
这里有两个问题,说注入整个服务容器应该解决这个问题.但是问题......见下文(注意尝试2和3之间的差异)......
试试1
public function __construct(SecurityContext $securityContext) {
$this->securityContext = $securityContext);
}
Run Code Online (Sandbox Code Playgroud)
Curcular Reference.好的 ...
试试2
public function __construct(ContainerInterface $container) {
$this->securityContext = $container->get('security.context');
}
Run Code Online (Sandbox Code Playgroud)
循环引用(为什么?,我在try 3中注入容器,除了我只有安全上下文)
试试3
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
Run Code Online (Sandbox Code Playgroud)
作品.
Kri*_*ith 24
发生这种情况是因为您的安全上下文依赖于此侦听器,可能是通过将实体管理器注入到用户提供程序中.最好的解决方案是将容器注入侦听器并懒惰地访问安全上下文.
我通常不喜欢将整个容器注入服务,但是使用Doctrine监听器进行异常处理,因为它们被急切地加载,因此应该尽可能地保持懒惰.
从Symfony 2.6开始,这个问题应该修复.拉取请求刚刚被主人接受.您的问题在此处描述. https://github.com/symfony/symfony/pull/11690
从Symfony 2.6开始,您可以将其security.token_storage注入您的监听器.此服务将包含SecurityContextin <= 2.5中使用的令牌.在3.0中,这项服务将SecurityContext::getToken()完全取代.您可以在此处查看基本更改列表:http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service
2.6中的示例用法:
你的配置:
services:
my.listener:
class: EntityListener
arguments:
- "@security.token_storage"
tags:
- { name: doctrine.event_listener, event: prePersist }
Run Code Online (Sandbox Code Playgroud)
你的倾听者
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class EntityListener
{
private $token_storage;
public function __construct(TokenStorageInterface $token_storage)
{
$this->token_storage = $token_storage;
}
public function prePersist(LifeCycleEventArgs $args)
{
$entity = $args->getEntity();
$entity->setCreatedBy($this->token_storage->getToken()->getUsername());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5754 次 |
| 最近记录: |