Symfony how to return all logged in Active Users

前端 未结 5 2046
-上瘾入骨i
-上瘾入骨i 2020-12-05 01:31

I want to return all Logged in users of my application and render it in my Dashboard. The user_id and user_name should be retrieve

5条回答
  •  猫巷女王i
    2020-12-05 02:02

    For Symfony3.4 (4), I used EntityManagerInterface to update user, and Security to get user, following codes worked for me :

    app/config/services.yml

    AppBundle\Service\ActivityListener:
        tags:
            - { name: 'kernel.event_listener', event: 'kernel.controller', method: onCoreController }
    

    Service/ActivityListener.php

    em = $em;
        $this->security = $security;
      }
    
      public function onCoreController(FilterControllerEvent $event)
      {
        // Check that the current request is a "MASTER_REQUEST"
        // Ignore any sub-request
        if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
            return;
        }
    
        // Check token authentication availability
        if ($this->security->getToken()) {
            $user = $this->security->getToken()->getUser();
    
            if ( ($user instanceof User) && !($user->isActiveNow()) ) {
                $user->setLastActivityAt(new \DateTime());
                $this->em->flush($user);
            }
        }
      }
    }
    

提交回复
热议问题