在Symfony 2.8 / 3.0中,使用我们新的安全组件,如何在不注入整个容器的情况下获取服务中当前记录的User
(即FOSUser)对象?
它甚至可能以非黑客的方式存在吗?
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
使用构造函数依赖注入,您可以这样做:
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class A
{
private $user;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->user = $tokenStorage->getToken()->getUser();
}
public function foo()
{
dump($this->user);
}
}
版本3.4中的新功能:安全实用程序类是在Symfony 3.4中引入的。
use Symfony\Component\Security\Core\Security;
public function indexAction(Security $security)
{
$user = $security->getUser();
}
https://symfony.com/doc/3.4/security.html#always-check-if-the-user-is-logged-in
在symfo 4中:
use Symfony\Component\Security\Core\Security;
class ExampleService
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function someMethod()
{
$user = $this->security->getUser();
}
}
见doc:https://symfony.com/doc/current/security.html#retrieving-the-user-object
来自Symfony 3.3
,仅来自Controller,根据这篇博文:https://symfony.com/blog/new-in-symfony-3-2-user-value-resolver-for-controllers
这很简单:
use Symfony\Component\Security\Core\User\UserInterface
public function indexAction(UserInterface $user)
{...}
Symfony在Symfony \ Bundle \ FrameworkBundle \ ControllerControllerTrait中执行此操作
protected function getUser()
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
if (null === $token = $this->container->get('security.token_storage')->getToken()) {
return;
}
if (!is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return;
}
return $user;
}
因此,如果您只是注入并替换security.token_storage
,那么你很高兴。
如果你扩展Controller类
$this->get('security.context')->getToken()->getUser();
或者,如果您有权访问容器元素..
$container = $this->configurationPool->getContainer();
$user = $container->get('security.context')->getToken()->getUser();
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements