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:-
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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With