Symfony 4:事件侦听器无法自动布线用户界面

2022-04-12 00:00:00 php symfony symfony4


当我将UserInterface添加到我的事件侦听器时,出现以下错误:

Cannot autowire service "AppEventListenerControllerListener": argument "$user" of method "__construct()" references interface "SymfonyComponentSecurityCoreUserUserInterface" but no such service exists. It cannot be auto-registered because it is from a different root namespace.


我不知道发生了什么,其他服务都运行得很好。 你能找找代码,告诉我我做错了什么吗?

~src/EventListener/ControllerListener.php

<?php
namespace AppEventListener;

use AppEntityUser;
use AppEntityDailyWin;
use AppControllerDailyWinController;
use PsrLogLoggerInterface;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpKernelEventFilterControllerEvent;
use SymfonyComponentSecurityCoreAuthorizationAuthorizationCheckerInterface;

class ControllerListener extends Controller implements DailyWinController
{
    private $authChecker, $user, $logger;

    public function __construct(UserInterface $user, AuthorizationCheckerInterface $authChecker, LoggerInterface $logger) {
        $this->user = $user;
        $this->authChecker = $authChecker;
        $this->logger = $logger;
    }

    public function onKernelController(FilterControllerEvent $event) {
        if ($this->authChecker->isGranted('IS_AUTHENTICATED_FULLY') === false) return;

        $this->logger->warning('Inicjowanie...');

        $em = $this->getDoctrine()->getManager();
        $DWrep = $em->getRepository(DailyWin::class);

        $userId = $this->user->getId();
        $userDailyWin = $DWrep->findOneBy(['userId' => $userId]);
        $this->logger->warning(print_r($userDailyWin));

        if (empty($userDailyWin)) {
            $currentDate = new DateTime(date('Y-m-d', time()));
            $userDailyWin = new DailyWin();
            $userDailyWin->setUserId($userId);
            $userDailyWin->setMultiplier(0);
            $userDailyWin->setClaimed(0);
            $userDailyWin->setStreak(0);
            $userDailyWin->setLastLogin($currentDate);

            $em->persist($userDailyWin);
            $em->flush();
        }
    }
}

谢谢。


解决方案

该用户不是symfony服务,将不会自动连接。

尝试使用此界面:

SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface

那么您需要:

$user=$tokenStorage->getToken()->getUser();

相关文章