更新时间:2023-02-12 19:37:14
您需要通过依赖项注入到您的侦听器类中以进行访问.
You need to inject the container via Dependency Injection into your listener class in order to acccess it.
在书籍章节中了解有关此内容的更多信息.
Read more about it in the book chapter.
your.listener:
class: Acme\MemberBundle\EventListener\CalendarEventListener
arguments: ["@service_container"]
尽管从性能角度来看,注入整个容器并不是***的主意,但还有其他一些原因,例如可测试性(通常应该只注入类中需要的服务,而不是注入容器)...
Though injecting the whole container is performance-wise not the best idea among with some other reasons like testability ( you should normally only inject the services you need in your class instead of the container )...
...如果您不使用UserCallable,则在注入@security.context
时会得到循环引用.
...in your case if you aren't using a UserCallable you will get a circular reference when injecting @security.context
.
所以最快的解决方案是注入容器并调整侦听器的构造函数:
So the quickest solution is injecting the container and adjusting your listener's constructor:
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function someOtherMethod()
{
$user = $this->container->get('security.context')->getToken()->getUser();
// ...
}