2017-02-17 92 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