我正在尝试将当前登录的用户注入监听器。我的目标是每次用户执行任何操作时都将当前的 \DateTime() 写入我的“demo_user”表的“last_active”列(这两种方法都不适用于我)。
应用程序/配置/config.yml
# ...
services:
demo.listener:
class: Demo\UserBundle\EventListener\ActivityWatcher.php
arguments: ['@service_container']
tags:
- { name: doctrine.event_listener, event: postLoad }
src/Demo/UserBundle/EventListener/ActivityWatcher.php
namespace Demo\UserBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Demo\UserBundle\Entity\DemoUser;
class ActivityWatcher
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
if ($entity instanceof DemoUser) {
$token = $this->container->get('security.context')->getToken();
$user = $token->getUser();
if($entity->getId() == $user->getId()) {
$entity->setLastActivity( new \DateTime() );
$entityManager->persist($entity);
$entityManager->flush();
}
}
}
}
但是 $token 总是空的......更新:没有提到,发生这种情况时我已经登录并通过了身份验证
FatalErrorException: Error: Call to a member function getUser()
on a non-object ...
有任何想法吗?啊,谢谢,扬
更新:
我也尝试只注入security.context:
arguments: ["@security.context"]
但有一个
ServiceCircularReferenceException: Circular reference detected for "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> wwk.listener -> security.context -> security.authentication.manager -> security.user.provider.concrete.administrators".