“Smart” Accessor in Doctrine Entity

Easily add some logic to filter out specific entities from an ArrayCollection in Symfony2. In this simple example, I wrote an app that had Node, and Comment entities separately, as well as an explicitly defined NodeComment entity. In my Node entity, I want to serialize all of the associated comments. But rather than call ->getNodeComments() and then filter in AngularJS (or Twig, or whatever else for that matter), I just want to know that my object node.comments are the actual comments I care about.

The Entity property

The Accessor

Now, my serialized object.comments are the actual comments, instead of the ManyToMany Entity.

Update User Entity on login

I recently built an app that required we update the authenticated user’s lastOnlineDate every session so we can quickly track who has been online in the last interval of time. We set this interval as a parameter and used that to avoid hitting the database more than absolutely necessary to accomplish this.

To make it work, we needed to leverage onSecurityInteractiveLogin:

app/config/parameters.yml

MyApp/EventListener/LoginListener.php

 

app/config/services.yml


Alternatives

In this particular use-case, leveraging a setContainer call may not be necessary if all you’re doing is setting a single value on a User entity. Alternatively, we could simply send the activity_minutes parameter as an argument to the service, and not use the container at all.

We’d have to adjust our LoginListener appropriately as well: