【发布时间】:2019-01-27 11:09:21
【问题描述】:
我的网站正在运行 Symfony 3.4,我创建了自己的用户会员系统。 我的用户实体包含一个日期时间字段“lastLogin”,每次用户登录时我都找不到更新它的解决方案。
我创建了一个自定义 UserChecker,然后我尝试更新其中的字段:
<?php
namespace CoreBundle\Security;
use CoreBundle\Entity\User as AppUser;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user)
{
if (!$user instanceof AppUser) {
return;
}
if ( $user->getDeleted() || !$user->getEnabled() )
{
throw new AuthenticationException();
}
else
{
// BELOW IS WHAT I TRY, BUT FAIL.
$entityManager = $this->get('doctrine')->getManager();
$user->setLastLogin(new \DateTime());
$entityManager->persist($user);
$entityManager->flush();
}
}
public function checkPostAuth(UserInterface $user)
{
if (!$user instanceof AppUser) {
return;
}
}
}
但它不起作用。也许我不能在这个文件中使用学说实体管理器?
如果我使用$this->get('doctrine')->getManager();,我会得到:
致命错误:调用未定义的方法 CoreBundle\Security\UserChecker::get()
【问题讨论】:
-
您的具体问题是什么?什么失败了?您收到任何错误消息吗?
-
它会给你任何错误。 .我想它会抛出关于没有可用的 get 函数的错误。 .对吗?
-
一个关于约定的非常小的建议:您不应该将 getDeleted 或 getEnabled 用于布尔方法,而应使用 isDeleted 和 isEnabled。
-
我编辑了我的第一个主题,但出现了错误。过失。
-
看起来您找到了解决方案。一个很好的。但是,如果您像下面的侦听器一样注入实体管理器,则上述代码将起作用。尽量避免在你的控制器中使用 getDoctrine。我可能会补充一点,最好使用直接 sql 更新您的数据库。如果您的代码的其他部分已经在使用实体管理器,那么刷新它可能会导致意外结果。
标签: symfony symfony-3.4 symfony-security