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

查看:80
本文介绍了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天全站免登陆