Chuck Norris Chuck Norris - 3 months ago 36
PHP Question

symfony 3 Doctrine LIstener service inject token_storage doesnt work

I have a doctrine listener which needs the get the current logged in user.

class DoctrineListener
{
/**
* @var null|TokenInterface
*/
private $token;

/**
* DoctrineListener constructor.
*
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->token = $tokenStorage->getToken();

var_dump($this->token);
}


and in my service.yml:

doctrine.listener:
class: AppBundle\EventListener\DoctrineListener
arguments:
- '@security.token_storage'
public: false
tags:
- { name: doctrine.event_listener, event: preFlush, method: preFlush }


The dump always returns me null when I try to use it in this listener.
I inject the token_storage_service in other services and it works well.

I'm under symfony 3.1, with a rest API.
And i send my authorizations header with Postman.

Can someone tell me what's wrong with my code ?

Thanks in advance.

Answer

Try to call $tokenStorage->getToken() in you preFlush method not in the constructor.