Ask your Symfony questions! Pay money and get answers fast! (more info)

What's the best way to get the current session|user object? Symfony


I have just written a simple Doctrine_Listener (read about it here) and in it I need to check whether the currently logged in user is the one that just logged in.

I currently get the session user with this:

$eventUser = sfContext::getInstance()->getUser()->getGuardUser()

Now we all know that sfContext::getInstance() is risky and usually a thing to avoid.

As I am just about to write a small unit test for this I will see the consequences soon.

NiKo suggested that I could use an event listener listening to context.load_factories and then fetch the user object and inject it in the listener. However this feels a bit intransparent for me.

Do you see a better approach?

Answers (1)


Pascal answers:

What about listening user.change_authentication event ?

you will have a myUser object as subject, a "authenticated" boolean as parameter and you will be able to access easily the sfGuardUser object.

Christian Schaefer comments:

Now that's not a bad idea!

But I tried the following callback and somehow when using link() the id of the loged in sfGuardUser is auto incremented which leads to all kinds of problems..

class UserLoginHistoryTable extends Doctrine_Table
public static function getInstance()
return Doctrine_Core::getTable('UserLoginHistory');

static public function writeLoginHistory(sfEvent $event)
$params = $event->getParameters();
if(true === $params['authenticated'])
$history = new UserLoginHistory();
$history->ip = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR');
$history->link('User', array($event->getSubject()->getGuardUser()->id));

I guess this happens because the event is fired before the sfGuardObject is saved. Though I haven't had a thorough look yet..

Any ideas?

Pascal comments:

You should try

$history->User = $event->getSubject()->getGuardUser();


$history->user_id = $event->getSubject()->getAttribute('user_id','','sfGuardSecurityUser');

Christian Schaefer comments:

That actually works fine. Thanks a lot!

And because it's so neat I put my stuff online for everybody:
[[LINK href=""]][[/LINK]]

and on GitHub as well:
[[LINK href=""]][[/LINK]]