Symfony2-将当前登录的用户注入到侦听器中 [英] Symfony2 - Inject the currently logged in user into a listener

查看:55
本文介绍了Symfony2-将当前登录的用户注入到侦听器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将当前登录的用户注入到侦听器中.我的目标是每次用户执行任何操作时都将当前\ DateTime()写入我的'demo_user'表的'last_active'列(这两个

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();
            }
        }
    }
}

但是$ token总是空的... 更新:没有提到,发生这种情况时我已经登录并通过了身份验证

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

更新:

我也只尝试注入security.context:

I also tried only to inject the security.context:

arguments: ["@security.context"]

但是得到了

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".

推荐答案

对于symfony 2.4,您应该可以插入表达式, 所以不是@service_container 使用 @=service('security.context').getToken().getUser()直接吸引用户

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

这篇关于Symfony2-将当前登录的用户注入到侦听器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆