phpsymfonyknpmenubundle

knpmenubundle: How to get user data in builder?


How can I get User data in theKnpMenuBundle's Builder?

I know I can get the user data via this line in Controller:

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

but I want it to get in my menu builder aswell, so I can put the username in the menu.


Solution

  • Your MenuBuilder is defined as a service in Symfony2, as you can see in https://github.com/KnpLabs/KnpMenuBundle/blob/master/Resources/doc/menu_service.rst

    Basically, all you need to do is configure your MenuBuilder service definition to inject the security context. (http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services)