Jonathan
Jonathan

Reputation: 3024

In Symfony2, how do you add a session to an anonymous user

The following code gets the current user whether they are logged in or not.

$token = $this->securityContext->getToken();
$user = $token->getUser();

If they are logged in a User object is returned, if they are anonymous String => "anon." is returned.

To add a session attribute to the user you do the following:

$user->setAttribute("monty", "python");

But if it's an anonymous user an error is thrown because $user is a non-object.

Upvotes: 0

Views: 1098

Answers (1)

Dincho Todorov
Dincho Todorov

Reputation: 350

There is service registered with key session, so in your controller you could do:

$this->get('session')->set('monty', 'python');

Upvotes: 3

Related Questions