Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Accessing the User

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

Accessing the User

Now that we’re logged in, how can we get access to the User object?

In a Template

Open up the homepage template. In Twig, we can access the User object by calling app.user. Let’s use it to print out the username:

{# src/Yoda/EventBundle/Resources/views/Event/index.html.twig #}

{# ... #}
{% if is_granted('IS_AUTHENTICATED_REMEMBERED') %}
    <a class="link" href="{{ path('logout') }}">
        Logout {{ app.user.username }}
    </a>
{% endif %}

Tip

If the user isn’t logged in, app.user will be null. So be sure to check that the user is logged in first before using app.user.

Accessing the User in a Controller

From a controller, it’s just as easy. Go to the controller function for the homepage and grab an object called the security context. Then call getToken() and getUser():

public function indexAction()
{
    $user = $this->container
        ->get('security.context')
        ->getToken()
        ->getUser()
    ;
    var_dump($user->getUsername());die;
    // ...
}

Actually, since this is a bit long, the Symfony base controller gives us a shortcut method called getUser:

public function indexAction()
{
    $user = $this->getUser();
    var_dump($user->getUsername());die;
    // ...
}

I showed you the longer option first so that you’ll understand that there is a service called security.context which is your key to getting the current User object. Remove this debug code before moving on.

Leave a comment!

0
Login or Register to join the conversation
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "~2.4", // v2.4.2
        "doctrine/orm": "~2.2,>=2.2.3", // v2.4.2
        "doctrine/doctrine-bundle": "~1.2", // v1.2.0
        "twig/extensions": "~1.0", // v1.0.1
        "symfony/assetic-bundle": "~2.3", // v2.3.0
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.5
        "symfony/monolog-bundle": "~2.4", // v2.5.0
        "sensio/distribution-bundle": "~2.3", // v2.3.4
        "sensio/framework-extra-bundle": "~3.0", // v3.0.0
        "sensio/generator-bundle": "~2.3", // v2.3.4
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "doctrine/doctrine-fixtures-bundle": "~2.2.0", // v2.2.0
        "ircmaxell/password-compat": "~1.0.3", // 1.0.3
        "phpunit/phpunit": "~4.1" // 4.1.0
    }
}
userVoice