Próbuję wprowadzić aktualnie zalogowanego użytkownika do odbiornika. Moim celem jest napisanie bieżącej \ DateTime() do kolumny "last_active" mojej tabeli "demo_user" za każdym razem, gdy użytkownik wykona jakąkolwiek akcję (obie metody this nie działają dla mnie).Symfony2 - Wstrzyknięcie aktualnie zalogowanego użytkownika do detektora
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();
}
}
}
}
Ale $ znacznik jest zawsze pusty ... AKTUALIZACJA: Nie wspomniałem, że jestem zalogowany i uwierzytelniony, gdy tak się stanie
FatalErrorException: Error: Call to a member function getUser()
on a non-object ...
Wszelkie pomysły? Arrgh, dzięki, Jan
UPDATE:
Próbowałem też tylko wstrzyknąć security.context:
arguments: ["@security.context"]
ale dostał
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".
ellegant nie jest rozwiązanie, ale: http://stackoverflow.com/questions/7561013/injecting- securitycontext-services-into-a-listener-class-in-symfony2-causes-circ –
Myślę, że dokładnie próbuję to zrobić w tej chwili, ale bez powodzenia – jxp315
Link podany przez @JovanPerovic jest w porządku. Prawidłowa odpowiedź jest następująca: http://stackoverflow.com/questions/7561013/injecting-securitycontext-into-a-listener-prepersist-lub-preupdate-in-symfony2-to#26011863 – webDEVILopers