如何在服务中获取当前登录的用户 [英] How to get the current logged User in a service

查看:26
本文介绍了如何在服务中获取当前登录的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Symfony 2.8/3.0 中,使用我们漂亮的新安全组件,如何在服务中获取当前登录的 User(即 FOSUser)对象 注入整个容器?<​​/p>

甚至可以以一种非黑客的方式吗?

PS:我们不要认为将其作为参数传递给服务函数"是显而易见的.还有,脏.

解决方案

security.token_storage 服务注入到你的服务中,然后使用:

$this->token_storage->getToken()->getUser();

如此处所述:http://symfony.com/doc/current/book/security.html#retrieving-the-user-object 和这里:http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services

In Symfony 2.8/3.0, with our fancy new security components, how do I get the currently logged User (i.e. FOSUser) object in a service without injecting the whole container?

Is it even possible in a non-hacky way?

PS: Let's not consider the "pass it to the service function as a parameter" for being trivially obvious. Also, dirty.

解决方案

Inject security.token_storage service into your service, and then use:

$this->token_storage->getToken()->getUser();

as described here: http://symfony.com/doc/current/book/security.html#retrieving-the-user-object and here: http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services

这篇关于如何在服务中获取当前登录的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆