Symfony 3.0.9 无法从我的服务访问 getUser()
Symfony 3.0.9 can't access getUser() from my service
我正在尝试使用以下服务从 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'
请问我做错了什么?
答案如下:
$tokenStorage = $this->container->get('security.token_storage')->getToken();
$user = $tokenStorage->getUser();
使用以下内容:
$this->container->get('security.token_storage')->getToken()->getUser();
无论如何,如果您只需要安全上下文,请避免注入整个容器。
https://symfony.com/doc/current/security.html#b-fetching-the-user-from-a-service
不要在服务中注入容器:
改为注入令牌存储。
seal_service:
class: FrontBundle\Service\SealService
public: true
arguments:
- ["@security.token_storage","@doctrine.orm.entity_manager"]
我正在尝试使用以下服务从 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'
请问我做错了什么?
答案如下:
$tokenStorage = $this->container->get('security.token_storage')->getToken();
$user = $tokenStorage->getUser();
使用以下内容:
$this->container->get('security.token_storage')->getToken()->getUser();
无论如何,如果您只需要安全上下文,请避免注入整个容器。
https://symfony.com/doc/current/security.html#b-fetching-the-user-from-a-service
不要在服务中注入容器: 改为注入令牌存储。
seal_service:
class: FrontBundle\Service\SealService
public: true
arguments:
- ["@security.token_storage","@doctrine.orm.entity_manager"]