我想在 Symfony 4.3.2 项目的 Controller 构造函数中获取用户对象。根据 https://symfony.com/doc/4.0/security.html#retrieving-the-user-object 上的文档,我只需要调用$this->getUser()。是的,这在操作方法中有效。
但是:尝试在构造函数中获取用户是行不通的,因为容器不会在这里初始化,并且 getUser 方法会抛出异常“Call to a member function has() on null”:容器为 null此时此刻。
这有效:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
public function indexAction()
{
dump($this->getUser());
}
}
这不会:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
public function __contruct()
{
dump($this->getUser());
}
public function indexAction()
{
}
}
当我手动注入(inject)容器时,一切都很好:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
public function __construct(ContainerInterface $container)
{
$this->container = $container;
dump($this->getUser());
}
public function indexAction()
{
}
}
顺便说一句,这是 AbstractController 中的 getUser 方法:
protected function getUser()
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
}
......
这是一个错误,容器没有在构造函数中初始化,还是一个功能,当您在构造函数中需要用户时,您必须手动初始化它?
编辑:使用https://symfony.com/blog/new-in-symfony-3-2-user-value-resolver-for-controllers中所示的方式在操作中确实有效,但在构造函数中不起作用:
....
private $user;
public function __construct(UserInterface $user)
{
$this->user = $user;
}
产生以下错误消息:无法 Autowiring 服务“App\Controller\TestController”:方法“__construct()”的参数“$user”引用接口(interface)“Symfony\Component\Security\Core\User\UserInterface”但不存在这样的服务。您是否创建了一个实现此接口(interface)的类?
。这就是我想设置用户对象的地方。
最佳答案
切勿使用 $security->getUser()
或$this->getUser()
在构造函数中!!
身份验证可能尚未完成。(在服务中,存储整个安全对象。:
symfony.com/doc/security.html#a-fetching-the-user-object
...您可以使用$this->getUser()
在任何通过 AbstractController 扩展的 Controller 中。 (只是不在构造函数中)
关于symfony - getUser() 方法在 Controller 构造函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57432903/