質問

I'm new to symfony and I'm trying to build a login system. I have a very simple relation to store the user

user(id:PK, name:string)

After a user has logged in, I store userId in his session like this

$session = new Session();
$session->set('userId', $user->getId());

I later use userId to fetch the user from the database and display personalized content. This is the code I have in my controller

$session = new Session();
$user = $this->getDoctrine()->getRepository('MyBundle:User')->find($session->get('userId'));

How do I tell symfony to automatically fetch the user at every request, without writing the code myself for every controller?

役に立ちましたか?

解決

Symfony has a pretty solid security system, you should implement your login system it's way. You can find information on how to integrate the traditional login system with a database in the Cookbook.

If you are authenticating your users this way, fetching the current user becomes easy:

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

Or, if you're inside a controller action:

$user = $this->getUser();

There's also the FOSUserBundle, which gives you some great tools to handle common user management at your system.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top