Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 - how to disable querying user at every page load?

I'm using my own User class as and entity provider for security system in symfony 2.0.

I noticed that on each reload of the page symfony is fetching user from db:

SELECT t0.id AS id1, t0.username AS username2, t0.salt AS salt3, t0.password AS password4, t0.email AS email5, t0.is_active AS is_active6, t0.credentials AS credentials7 FROM w9_users t0 WHERE t0.id = ? Parameters: ['23'] Time: 4.43 ms

Is there any easy way to disable this behaviour? Maybe serialize user data in session variables or cache them some way?

like image 996
dunqan Avatar asked Apr 08 '12 07:04

dunqan


1 Answers

You can change this behavior in the refreshUser method of your UserProvider.

You should be careful when doing this with doctrine: There is an issue at FosUserBundle github, explaining the pitfalls:

Storing it in the session would lead to several issues, which is why it is not done by default:

if an admin change the permissions of a user, the changes will have an effect only the next time you retrieve the user from the database. So caching the user must be done carefully to avoid security issues

if you simply reuse the user which was serialized in the session, it will not be managed by Doctrine anymore. This means that as soon as you want to modify the user or to use the user in a relation, you will have to merge it back into the UnitOfWork (which will return a different object than the one used by the firewall). Merging will trigger a DB query too. And requiring such logic will break some of the built-in controller which are expecting to be able to use the user object for updates.

like image 165
Hakan Deryal Avatar answered Nov 11 '22 02:11

Hakan Deryal