douyan1896 2014-08-29 19:13
浏览 36
已采纳

在Symfony2中,如何向匿名用户添加会话

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.

  • 写回答

1条回答 默认 最新

  • drwn65609 2014-08-29 20:24
    关注

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

    $this->get('session')->set('monty', 'python');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?