2017-02-17 25 views
0

我願意爲用戶登錄創建監聽器,以便在用戶成功登錄時更新登錄計數和上次登錄數據到數據庫。登錄監聽器中的Symfony 3用戶存儲庫

我得到的用戶信息成功,但不能訪問他們,不能更新數據庫

的src /的appbundle /監聽器/ SecurityListener.php:

namespace AppBundle\Listener; 
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; 
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; 
#use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; 
use Doctrine\ORM\EntityManager; 

class SecurityListener 
{ 
    private $tokenStorage; 

    public function __construct(TokenStorage $tokenStorage, EntityManager $doctrine) 
    { 

    } 

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) 
    { 
    if ($event->getAuthenticationToken()->isAuthenticated()) { 
     $user = $event->getAuthenticationToken()->getUser(); 
      var_dump($user->id); 
    } 

    /** 
    * Update lastLogin and loginCount for user in database 
    */ 

    $em = $this->getDoctrine()->getManager(); 
     $user = $em->getRepository('AppBundle:User')->find($user->id); 

     if(!$user) 
     { 
      throw $this->createNotFoundException(
       'User could not be found for id '. $user->id 
      ); 
     } 

     $user->setLastLogin(date()); 
     $user->setLoginCount($user->loginCount +1); 
     $em->flush; 


    } 

} 

錯誤:

Error: Cannot access private property AppBundle\Entity\User::$id 

回答

0

實體屬性通常是私有的,但您始終可以使用getter方法。

請更新您的代碼類似於此示例:

throw $this->createNotFoundException(
    'User could not be found for id '. $user->getId() 
); 

您也可以嘗試的方法稱爲getID(),如果我的例子失敗。

+0

我在用戶實體中有方法getId(),它不起作用,我得到錯誤'注意:未定義的屬性:AppBundle \ Entity \ User :: $ getId'。我假設我在這裏有一些小小的誤解...... – Diamonte

+0

讓我看看產生這個通知的代碼 –

+0

對不起,它適用於$ user-> getId()....之後我只有隱形字符它返回的錯誤...你的答案是固定的,所以爲了得到想要的數據,我必須使用getter方法 – Diamonte