Symfony 4:事件监听器无法自动装配UserInterface

时间:2017-12-24 21:35:59

标签: php symfony symfony4


当我将UserInterface添加到我的事件监听器时,我有以下错误:

Cannot autowire service "App\EventListener\ControllerListener": argument "$user" of method "__construct()" references interface "Symfony\Component\Security\Core\User\UserInterface" but no such service exists. It cannot be auto-registered because it is from a different root namespace.


我不知道发生了什么,其他服务工作正常。 你能找代码并告诉我我做错了什么吗?

〜SRC /事件监听/ ControllerListener.php

<?php
namespace App\EventListener;

use App\Entity\User;
use App\Entity\DailyWin;
use App\Controller\DailyWinController;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

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

感谢。

3 个答案:

答案 0 :(得分:6)

用户不是symfony服务,它不会自动装配。

尝试使用此界面:

Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface

然后你做:

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

答案 1 :(得分:0)

从Symfony 3.2开始,引入了一个新的用户解析器。它似乎不允许通过构造函数注入(我也试图使这个工作),但你应该注入你的方法。

public function onKernelController(UserInterface $user , FilterControllerEvent $event) {

根据documentation

答案 2 :(得分:0)

迟到聚会,但是在控制器中,您也可以使用:

repeat = 1
for i in range(0, len(myList), 1000):
    for j in range(i, 1000*repeat):
        if j+1 <= len(myList):
            tempList.append(myList[j])
    //Further processing logic
    tempList = []
    repeat += 1

从Symfony 3.2开始,请参见here