如何在Symfony2中获取代表当前用户的实体? [英] How do I get the entity that represents the current user in Symfony2?

查看:81
本文介绍了如何在Symfony2中获取代表当前用户的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Symfony安全设置。一切正常,但我不知道如何做一件重要的事情:



在twig中,我可以通过以下方式达到当前用户的信息:

 欢迎,{{app.user.username}} 

或类似



如何在Controller中访问相同的信息?具体来说,我想获取当前的用户实体,所以我可以将它关联存储在另一个实体中(一对一映射)。



我真的希望它能

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

但这不行。它给了我一个类型

  Symfony\Component\Security\Core\User\User 

我想要一种类型

  Acme\AuctionBundle\Entity\User 

这是我的实体。 ...

解决方案

正如ktolis所说,你首先必须配置你的 / app / config / security



然后与

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

应该enougth!



$ usr 是您的用户对象!您不需要再次查询。



找出在 security.yml 从 Sf2文档,然后再试一次。



祝你好运!






strong>编辑:从symfony 2.6, security.context 服务已弃用,使用 security.token_storage 服务作为:

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


I am using the Symfony security setup. Everything works fine, but I don't know how to do one important thing:

In twig, I can reach the current user's info by doing:

Welcome, {{ app.user.username }}

or similar

How do I access this same information in the Controller? Specifically, I want to get the current user entity so I can store it relationally in another entity (one-to-one mapping).

I was really hoping it'd be

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

but that doesn't work. It gives me a class of type

Symfony\Component\Security\Core\User\User

and I want one of type

Acme\AuctionBundle\Entity\User

which is my entity....

解决方案

As ktolis says, you first have to configure your /app/config/security.yml.

Then with

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

should be enougth!

$usr is your User Object! You don't need to query it again.

Find out the way to set up your providers in security.yml from Sf2 Documentation and try again.

Best luck!


EDIT: from symfony 2.6, security.context service is deprecated, use security.token_storage service as:

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

这篇关于如何在Symfony2中获取代表当前用户的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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