Symfony2登录用户的ID [英] Symfony2 getting logged in user's id

查看:117
本文介绍了Symfony2登录用户的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Symfony2和doctrine 2开发应用程序。我想知道如何获取当前登录的用户的ID。

I am developing an application using Symfony2 and doctrine 2. I would like to know how can I get the currently logged in user's Id.

推荐答案

Symfony 2.6 开始,您可以从安全令牌存储中检索用户,例如您的控制器:

As of Symfony 2.6 you can retrieve a user from the security token storage, for example in your controller:

$user = $this->get('security.token_storage')->getToken()->getUser();

在Symfony 2.6 之前,令牌可以从安全上下文服务中访问:

Before Symfony 2.6, the token was accessible from the security context service instead:

$user = $this->get('security.context')->getToken()->getUser();

安全上下文服务已被弃用,将在Symfony 3.0中删除。

如果扩展基本控制器,还可以使用快捷方式:

If you extend the base controller, you can also use a shortcut method:

$user = $this->getUser();

然后你可以得到你想要的东西:

Then you can get whatever your want:

$userId = $user->getId();

当然,您的用户类需要实现getId()方法。

Of course your user class needs to implement the getId() method.

所有这些都在文档中描述: http ://symfony.com/doc/current/book/security.html#retrieving-the-user-object

All of this is described in the documentation: http://symfony.com/doc/current/book/security.html#retrieving-the-user-object

有关安全性的更多内容: http://symfony.com/doc/current/book/security.html#来自数据库的加载用户

More on security here: http://symfony.com/doc/current/book/security.html#loading-users-from-the-database

这篇关于Symfony2登录用户的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆