[当用户登录系统时,我需要在类变量(Login-> testInfo)中填充信息,但是在控制器中,该变量始终返回null。
这里是一个通用示例。
登录类
class Login extends UserInterface
{
private $testInfo = null;
public function setTestInfo(string $testInfo)
{
$this->testInfo = $testInfo;
}
public function getTestInfo() : ?string
{
return $this->testInfo;
}
}
验证者:
class FormAuthenticator extends AbstractFormLoginAuthenticator
{
...
public function getUser($credentials, UserProviderInterface $userProvider)
{
$user = $this->entityManager->getRepository(Login::class)->findByUsername(credentials['username']);
if (!$user)
{
throw new CustomUserMessageAuthenticationException('Username could not be found.');
}
//this prints NULL
dd($user->getTestInfo());
$user->setTestInfo('testing the string');
//this prints 'testing the string'
dd($user->getTestInfo());
return $user;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
//this prints 'testing the string'
dd($token->getUser()->getTestInfo());
}
...
}
控制器类:
class MyController extends AbstractController
{
private $login = null;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->login = $tokenStorage->getToken() ? $tokenStorage->getToken()->getUser() : null;
}
public function home()
{
//this prints null
dd($this->login->getTestInfo());
}
}
如果$ user使用新值进入tokenStorage('测试字符串'),为什么当我尝试在控制器上使用它时,变量始终返回null?我在做什么错?
testInfo
是瞬态变量吗?因为您必须知道UserProvider
会尝试从令牌刷新用户(可能在请求之间可能会“更改”)。我很确定您会在此过程中丢失这些信息。
您确定在身份验证成功事件将令牌写入令牌存储服务之前,您的控制器构造函数执行得还不是太早?我希望在构造函数中使用UserProvider
令牌,以验证此时是否存在令牌和Login实例。
您可能需要在控制器中使用dd()
而不是setContainer()
来检索经过身份验证的令牌,这看起来像这样:
__construct()