Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - Inject the currently logged in user into a listener

I am trying to inject the currently logged in user into a Listener. My goal is to write a current \DateTime() to the 'last_active' column of my 'demo_user' table every time the user does any action (both of this this methods do not work for me) .

app/config/config.yml

# ...
services:
    demo.listener:
        class: Demo\UserBundle\EventListener\ActivityWatcher.php
        arguments: ['@service_container']
        tags:
            - { name: doctrine.event_listener, event: postLoad }

src/Demo/UserBundle/EventListener/ActivityWatcher.php

namespace Demo\UserBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Demo\UserBundle\Entity\DemoUser;

class ActivityWatcher
{

    protected $container;

    public function __construct(ContainerInterface $container)
    {   
        $this->container = $container;
    }


    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        if ($entity instanceof DemoUser) {
            $token = $this->container->get('security.context')->getToken();
            $user = $token->getUser();

            if($entity->getId() == $user->getId()) {
                $entity->setLastActivity( new \DateTime() );
                $entityManager->persist($entity);
                $entityManager->flush();
            }
        }
    }
}

But the $token is always empty... UPDATE: Didn't mention, that I'm logged in and authenticated when this happens

FatalErrorException: Error: Call to a member function getUser()
on a non-object ...

Any ideas? Arrgh, thanks, Jan

UPDATE:

I also tried only to inject the security.context:

arguments: ["@security.context"]

but got a

ServiceCircularReferenceException: Circular reference detected for "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> wwk.listener -> security.context -> security.authentication.manager -> security.user.provider.concrete.administrators".
like image 208
jxp315 Avatar asked Jul 26 '13 20:07

jxp315


1 Answers

for symfony 2.4 you should be able to inject expression, so instead of @service_container use @=service('security.context').getToken().getUser() to get user directly

like image 144
kshishkin Avatar answered Oct 02 '22 15:10

kshishkin