我想將當前登錄的用戶注入偵聽器。我的目標是每次用戶執行任何操作時(這兩個this方法都不適用於我),將'CurrentTime()'寫入'demo_user'表的'last_active'列。Symfony2 - 將當前登錄的用戶注入偵聽器
應用程序/配置/ config.yml
# ...
services:
demo.listener:
class: Demo\UserBundle\EventListener\ActivityWatcher.php
arguments: ['@service_container']
tags:
- { name: doctrine.event_listener, event: postLoad }
的src /演示/ UserBundle /事件監聽/ 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();
}
}
}
}
但是$令牌總是空... 更新:沒有提及,我登錄並在發生這種情況時進行身份驗證
FatalErrorException: Error: Call to a member function getUser()
on a non-object ...
任何想法? Arrgh,謝謝,揚
UPDATE:
我也只是試圖注入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".
不是一個ellegant解決方案,但:http://stackoverflow.com/questions/7561013/injecting- securitycontext-services-into-a-listener-class-in-symfony2-causes-circ –
我想我現在正在嘗試這樣做,但沒有成功 – jxp315
@JovanPerovic提供的鏈接很好。正確的答案是這一個:http://stackoverflow.com/questions/7561013/injecting-securitycontext-into-a-listener-prepersist-or-preupdate-in-symfony2-to#26011863 – webDEVILopers