Symfony2: Inject current user in Service

后端 未结 7 1974
夕颜
夕颜 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:36

    I would recommend binding a different event, if you use the kernel.controller event, you will have a token and have no problem. The token is not available in kernel.request since Symfony 2.3

    I wrote a guide on how to implement User Timezones for Symfony 2.3+ and 2.6+ in Twig on my blog called Symfony 2.6+ User Timezones.

    This is vastly superior to using a Twig Extension because you can use the standard date formatting functions in Twig, as well as provide separate backend UTC date, default Twig date timezones and User defined Twig date timezones.

    Here is the most important excerpt:

    src/AppBundle/EventListener/TwigSubscriber.php

    <?php
    
    namespace AppBundle\EventListener;
    
    use AppBundle\Entity\User;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class TwigSubscriber implements EventSubscriberInterface
    {
        protected $twig;
        protected $tokenStorage;
    
        function __construct(\Twig_Environment $twig, TokenStorageInterface $tokenStorage)
        {
            $this->twig = $twig;
            $this->tokenStorage = $tokenStorage;
        }
    
        public static function getSubscribedEvents()
        {
            return [
                'kernel.controller' => 'onKernelController'
            ];
        }
    
        public function onKernelController(FilterControllerEvent $event)
        {
            $token = $this->tokenStorage->getToken();
    
            if ($token !== null) {
                $user = $token->getUser();
    
                if ($user instanceof User) {
                    $timezone = $user->getTimezone();
                    if ($timezone !== null) {
                        $this->twig->getExtension('core')->setTimezone($timezone);
                    }
                }
            }
        }
    }
    

    Now you can use twig as normal and it uses your User preferences if available.

    0 讨论(0)
提交回复
热议问题