Symfony2: Inject current user in Service

后端 未结 7 2020
夕颜
夕颜 2020-12-25 10:37

I am trying to inject the currently logged in user into a service. My goal is to extend some twig functionality to output it based on user preferences. In this example I wan

7条回答
  •  佛祖请我去吃肉
    2020-12-25 11:25

    From Symfony 2.6.

    You need use @security.token_storage

    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class UserDateExtension extends \Twig_Extension
    {
    /**
     * @var TokenStorageInterface
     */
    protected $tokenStorage;
    
    
    /**
     * @param $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
    }
    

    }

    And Services.yml

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

    reference: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

提交回复
热议问题