TokenStorage sometimes returns null in Service

谁说我不能喝 提交于 2019-12-30 17:21:52

问题


I have a Service that get's the current logged in user, which only works some of the time whilst in the dev environment.

The problem seems to be whenever I change the Twig templates and refresh I get the error:

Error: Call to a member function getUser() on null

If I refresh the page everything works as it should until I update the Twig template again. This obviously makes development very slow as I'm constantly refreshing the page.

Things I have done so far:-

  1. Cleared the dev environment cache.
  2. Cleared the browser cache.
  3. Confirmed the user is definitely logged in (otherwise it wouldn't work the on the second refresh)

Does anyone have any ideas what could be causing the problem?

services.yml

myservice:
    class: AppBundle\Services\MyService
    arguments: ["@doctrine.orm.entity_manager", "@security.token_storage"]

MyService.php

<?php
namespace AppBundle\Services;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class MyService
{
    private $em;
    private $token;

    public function __construct($entityManager, TokenStorageInterface $tokenStorage)
    {
        $this->em = $entityManager;
        $this->token = $tokenStorage->getToken();
    }

    public function doSomething()
    {
        $user_id = $this->token->getUser()->getID();
        return;
    }
}

Twig Template

{{ myservice.doSomething }}

Note: This is the bare-bones code that still causes the problem


回答1:


I'm not certain, but it looks to me like your class should maintain a pointer to the tokenStorage class, not the token itself (as this may change). Your service would then look like this:

class MyService
{
   private $em;
   private $tokenStorage;

   public function __construct($entityManager, TokenStorageInterface $tokenStorage)
   {
       $this->em = $entityManager;
       $this->tokenStorage = $tokenStorage;
   }

   public function doSomething()
   {
       $user_id = $this->tokenStorage->getToken()->getUser()->getID();
       return;
   }
}


来源:https://stackoverflow.com/questions/32590621/tokenstorage-sometimes-returns-null-in-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!