2013-07-26 28 views
8

我想將當前登錄的用戶注入偵聽器。我的目標是每次用戶執行任何操作時(這兩個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". 
+0

不是一個ellegant解決方案,但:http://stackoverflow.com/questions/7561013/injecting- securitycontext-services-into-a-listener-class-in-symfony2-causes-circ –

+0

我想我現在正在嘗試這樣做,但沒有成功 – jxp315

+0

@JovanPerovic提供的鏈接很好。正確的答案是這一個:http://stackoverflow.com/questions/7561013/injecting-securitycontext-into-a-listener-prepersist-or-preupdate-in-symfony2-to#26011863 – webDEVILopers

回答

2

symfony 2.4,你應該能夠注入表達, 所以不是@service_container 使用 @=service('security.context').getToken().getUser()讓用戶直接

+2

嗨,我試過這個,但我有同樣的問題:*服務「doctrine.orm.default_entity_manager」*檢測到循環引用。它看起來像在調用'@ security.context'時使用'doctrine.event_listener'仍然會引發錯誤。 –

+0

這對我來說非常合適。謝謝Symfony精靈 –

0

解決循環引用問題當注入當前用戶正在實現可調用的用戶。

您可以使用由KnpDoctrineBehaviors提供的UserCallable類。

首先,您需要從用戶可調用類中創建一個服務,並將容器注入其中。

您可以在KnpDoctrineBehaviors提供的配置中找到有關如何執行此操作的YML示例。

現在將您的UserCallable服務注入到您的監聽器中,並從用戶調用用戶可調用,如source of Blameable listener中所示。