Injecting the whole container directly into the lister may be a working solution ... but we can do better :)
Inject a UserCallable that returns the current user instead.
This way you express the real purpose of the depedency more clearly without introducing a hard dependency between your listener and the container(-interface). An example would be ...
Knp\DoctrineBehaviors\ORM\Blameable\UserCallable
This particular example can be improved further by creating an interface and using that for type-hinting in your listener instead. That allows easier exchangeability if you plan to re-use the listener.
The interfaces:
namespace Acme\Common;
interface UserCallableInterface
{
/**
* @return \Symfony\Component\Security\Core\User\UserInterface
*/
public function getCurrentUser();
}
namespace Acme\Common;
use Symfony\Component\Security\Core\User\UserInterface;
interface TrackableInterface
{
/**
* @param UserInterface $user
*/
public function setUser(UserInterface $user);
}
The UserCallable:
namespace Acme\Util;
use Acme\Common\UserCallableInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UserCallable implements UserCallableInterface
{
/** @var ContainerInterface **/
protected $container;
/**
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @{inheritdoc}
*/
public function getCurrentUser()
{
return $this->container->get('security.context')->getToken()->getUser() ?: false;
}
The listener:
use Acme\Common\UserCallableInterface;
use Acme\Common\TrackableInterface;
use Doctrine\Common\EventArgs;
class Listener
{
/** @var UserCallableInterface **/
protected $userCallable;
/**
* @param UserCallableInterface $user_callable
**/
public function __construct(UserCallableInterface $user_callable)
{
$this->userCallable = $user_callable;
}
/**
* @param EventArgs $args
**/
public function onPrePersist(EventArgs $args)
{
$entity = $args->getEntity();
if ( !($entity instanceof TrackableInterface) ) {
return;
}
if ( !($user = $this->userCallable->getCurrentUser())) {
return;
}
$entity->setUser($user);
}
}