title: How to store user last access in DB
body: <p>I'm writing a Web App using Symfony2 and I need to register the last access of every user who log in to the app. My entity has a <code>last_access</code> property, type datetime. </p>
  
  <p>The code is easy, I just need to get the entity of the current user and set the value, but I don't know where I have to put that code. </p>
  
  <p>I was thinking in something like this:</p>
  
  <pre><code>$manager = $this-&gt;getDoctrine()-&gt;getManager();
  $user= $this-&gt;get('security.context')-&gt;getToken()-&gt;getUser();
  $user-&gt;setLastAccess(new \DateTime('now'));
  $manager-&gt;persist($user);
  $manager-&gt;flush();
  </code></pre>
  
  <h2>UPDATE</h2>
  
  <p>I solved this using an event listener.</p>
  
  <pre><code>class LoginListener {
  /**
   * @var Doctrine\Bundle\DoctrineBundle\Registry
   */
  private $doctrine;
  
  public function __construct(Doctrine $doctrine){
      $this-&gt;doctrine = $doctrine;
  }
  
  public function onInteractiveLogin(InteractiveLoginEvent $event){
      $user = $event-&gt;getAuthenticationToken()-&gt;getUser();
  
      if ($user) {
          $user-&gt;setLastAccess(new \DateTime('now'));
          $this-&gt;doctrine-&gt;getEntityManager()-&gt;persist($user);
          $this-&gt;doctrine-&gt;getEntityManager()-&gt;flush();
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Also I created a service:</p>
  
  <pre><code>services:
  my.service:
      class: SGRH\AdminBundle\Listener\LoginListener
      arguments: [@doctrine]
      tags:
        - { name: kernel.event_listener, event: security.interactive_login, method: onInteractiveLogin }
  </code></pre>
  
  <p>Thanks to everyone!</p>