Symfony2: Inject current user in Service Symfony2: Inject current user in Service symfony symfony

Symfony2: Inject current user in Service


I think that this question deserves an updated answer since 2.6.x+ since the new security component improvements.

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;class UserDateExtension extends \Twig_Extension{    /**     * @var TokenStorage     */    protected $tokenStorage;    /**     * @param \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage    $tokenStorage     */    public function __construct(TokenStorage $tokenStorage)    {        $this->tokenStorage = $tokenStorage;    }    public function getUser()    {        return $this->tokenStorage->getToken()->getUser();    }    public function getFilters()    {        return array(            'user_date' => new \Twig_Filter_Method($this, "formatUserDate"),        );    }    public function formatUserDate($date, $format)    {        $user = $this->getUser();        // do stuff    }}

Services.yml

twig.date_extension:    class: Acme\Twig\SpecialDateExtension    tags:        - { name: twig.extension }    arguments:        - "@security.token_storage"


I would use a twig extension for that:

class UserDateExtension extends \Twig_Extension{    private $context;    public function __construct(SecurityContext $context)    {        $this->context = $context;    }    public function getUser()    {        return $this->context->getToken()->getUser();    }    public function getFilters()    {        return array(            'user_date' => new \Twig_Filter_Method($this, "formatUserDate"),        );    }    public function formatUserDate($date, $format)    {        $user = $this->getUser();        // do stuff    }

Now in services.xml

    <service id="user_date_twig_extension" class="%user_date_twig_extension.class%">        <tag name="twig.extension" />        <argument type="service" id="security.context" />    </service>

Then in twig you could do:

{{ date | user_date('d/m/Y') }}


services.yml

my_service:    class: ...    arguments:        - "@=service('security.token_storage').getToken().getUser()"

Service.php

protected $currentUser;public function __construct($user){    $this->currentUser = $user;}

http://symfony.com/doc/current/book/service_container.html#using-the-expression-language