我正在尝试使用以下命令通过symfony 3.0.9中的服务访问用户:
在我的service.yaml中:
seal_service:
class: FrontBundle\Service\SealService
public: true
arguments:
- "@service_container"
我的服务是这样的:
class SealService
{
protected $container = null;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getAvailableSeals($sn = null){
$user = $this->container->get('fos_user.user_manager')->getUser();
...
}
但是出现以下错误:
Attempted to call an undefined method named "getUser"
我也尝试过$this->container->get('fos_user.user_manager')
如果我使用$this->container->get('fos_user.security.controller')
,我会得到Call to protected method Symfony\Bundle\FrameworkBundle\Controller\Controller::getUser() from context 'FrontBundle\Service\SealService'
我在做什么错了?
答案 0 :(得分:2)
不要在使用中注入容器: 而是注入令牌存储。
seal_service:
class: FrontBundle\Service\SealService
public: true
arguments:
- ["@security.token_storage","@doctrine.orm.entity_manager"]
答案 1 :(得分:1)
这是答案:
$tokenStorage = $this->container->get('security.token_storage')->getToken();
$user = $tokenStorage->getUser();
答案 2 :(得分:0)
使用以下内容:
$this->container->get('security.token_storage')->getToken()->getUser();
无论如何,如果只需要安全上下文,请避免注入整个容器。
https://symfony.com/doc/current/security.html#b-fetching-the-user-from-a-service