-->

TokenStorage sometimes returns null in Service

2019-02-21 13:30发布

问题:

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;
   }
}


标签: symfony-2.6