I am using symfony2 and FOSUserBundle.
Normally,I can get user data from Controller
$user = $this->get(\'security.context\')->getToken()->g
You need to inject the container via Dependency Injection into your listener class in order to acccess it.
Read more about it in the book chapter.
your.listener:
class: Acme\MemberBundle\EventListener\CalendarEventListener
arguments: ["@service_container"]
Though injecting the whole container is performance-wise not the best idea among with some other reasons like testability ( you should normally only inject the services you need in your class instead of the container )...
...in your case if you aren't using a UserCallable you will get a circular reference when injecting @security.context
.
So the quickest solution is injecting the container and adjusting your listener's constructor:
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function someOtherMethod()
{
$user = $this->container->get('security.context')->getToken()->getUser();
// ...
}
As of Symfony 2.6 this issue should be fixed. A pull request has just been accepted into the master. Your problem is described in here. https://github.com/symfony/symfony/pull/11690
As of Symfony 2.6, you can inject the security.token_storage
into your listener. This service will contain the token as used by the SecurityContext
in <=2.5. In 3.0 this service will replace the SecurityContext::getToken()
altogether. You can see a basic change list here: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service
Example usage in 2.6:
Your configuration:
services:
my.listener:
class: EntityListener
arguments:
- "@security.token_storage"
tags:
- { name: doctrine.event_listener, event: prePersist }
Your Listener
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class EntityListener
{
private $token_storage;
public function __construct(TokenStorageInterface $token_storage)
{
$this->token_storage = $token_storage;
}
public function prePersist(LifeCycleEventArgs $args)
{
$entity = $args->getEntity();
$entity->setCreatedBy($this->token_storage->getToken()->getUsername());
}
}
Be sure to not have the Symfony profiler/toolbar
turned on. I don't know why, but that made $this->container->get('security.context')->getToken()
return null
every time.
In the file, config_dev.yml
make sure the following is set:
web_profiler:
toolbar: false