Accessing logged in user in Symfony2 from php template

My question is how can I access the logged in user from the view? I know it's possible with twigs {app.user}, but I have to do it in php template. Is it possible to get the user from php template? Something like $app->getUser() or something?

Upvotes: 0

Views: 46

Answers (2)

Cristian Angulo Nova
Cristian Angulo Nova

Reputation: 451

To allow the user to log in using Twig templates magic method {{ app.user.username }}

Upvotes: 0

lxg
lxg

Reputation: 13107

You can access the user through the security.context service. For example, you could write in your controller:

$User = null;
$securityToken = $this->container->get('security.context')->getToken();

if (is_object($securityToken) && is_callable([$securityToken, 'getUser']))
    $User = $securityToken->getUser();

Note: It is possible that the $User variable does not really contain your user entity. In this case, you should additionally check that $User is an instance of your user entity:

… && is_object($User) && is_callable([$User, 'getId']) && $User->getId() …

Upvotes: 1

Related Questions