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

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

问题描述

我正在使用 Symfony2 和学说 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 版本(Symfony 4,Symfony >=3.2)

自从 Symfony >=3.2 您可以简单地期望将 UserInterface 实现直接注入到您的控制器操作中.然后您可以调用 getId() 来检索用户的标识符:

Since Symfony >=3.2 you can simply expect a UserInterface implementation to be injected to your controller action directly. You can then call getId() to retrieve user's identifier:

class DefaultController extends Controller
{
    // when the user is mandatory (e.g. behind a firewall)
    public function fooAction(UserInterface $user)
    {
        $userId = $user->getId(); 
    }

    // when the user is optional (e.g. can be anonymous)
    public function barAction(UserInterface $user = null) 
    {
        $userId = null !== $user ? $user->getId() : null;
    }
}

自 2.6 以来,您仍然可以像在所有 Symfony 版本中一样使用安全令牌存储.例如,在您的控制器中:

You can still use the security token storage as in all Symfony versions since 2.6. For example, in your controller:

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

请注意,不再鼓励使用本答案下一部分中提到的 Controller::getUser() 快捷方式.

Note that the Controller::getUser() shortcut mentioned in the next part of this answer is no longer encouraged.

旧版 Symfony 版本

过去访问用户的最简单方法是扩展基本控制器,并使用快捷方式getUser() 方法:

The easiest way to access the user used to be to extend the base controller, and use the shortcut getUser() method:

$user = $this->getUser();

Symfony 2.6 起,您可以从安全令牌存储中检索用户:

Since Symfony 2.6 you can retrieve a user from the security token storage:

$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 2 中已被弃用,并在 Symfony 3.0 中被删除.

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

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