Symfony2: Inject current user in Service

后端 未结 7 2023
夕颜
夕颜 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:20

    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"
    

提交回复
热议问题