无法在 Symfony 3.4 和 FosUserBundle 中自动装配服务

Cannot autowire service in Symfony 3.4 and FosUserBundle

我尝试覆盖 FosUserBundle 中的 REGISTRATION_SUCCESS,以便在注册新用户后将管理员重定向到用户列表。

所以我创建了一个新的事件订阅者:

<?php
namespace AppBundle\EventListener;

use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Mailer\MailerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class RedirectAfterRegistrationSubscriber implements EventSubscriberInterface
{
    private $mailer;
    private $tokenGenerator;
    private $router;

    public function __construct(MailerInterface $mailer, TokenGeneratorInterface $tokenGenerator, UrlGeneratorInterface $router)
    {
        $this->mailer = $mailer;
        $this->tokenGenerator = $tokenGenerator;
        $this->router = $router;
    }

    public function onRegistrationSuccess(FormEvent $event)
    {
        $user = $event->getForm()->getData();

        $user->setEnabled(false);
        if (null === $user->getConfirmationToken()) {
            $user->setConfirmationToken($this->tokenGenerator->generateToken());
        }

        $this->mailer->sendConfirmationEmailMessage($user);

        $url = $this->router->generate('user_index');
        $event->setResponse(new RedirectResponse($url));
    }

    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess'
        ];
    }
}

和以下服务:

app.redirect_after_registration_subscriber:
    class: AppBundle\EventListener\RedirectAfterRegistrationSubscriber
    arguments: ['@fos_user.mailer', '@fos_user.util.token_generator', '@router']
    tags:
        - { name: kernel.event_subscriber }

我不明白为什么会出现这个错误:

Cannot autowire service "AppBundle\EventListener\RedirectAfterRegistrationSubscriber": 
argument "$mailer" of method "__construct()" references interface 
"FOS\UserBundle\Mailer\MailerInterface" but no such service exists. You should maybe alias
this interface to one of these existing services: "fos_user.mailer.default",
"fos_user.mailer.twig_swift", "fos_user.mailer.noop".

我想您正在使用自动发现服务。类似于:

# services.yaml

AppBundle\:
    resource: '../src/'
...

因此,除了您定义的 @app.redirect_after_registration_subscriber 之外,Symfony 还定义了另一个 ID 为 @AppBundle\EventListener\RedirectAfterRegistrationSubscriber 的服务。两者都指向 AppBundle\EventListener\RedirectAfterRegistrationSubscriber class。但是你只为第一个配置了mailer参数

解决方法:

AppBundle\EventListener\RedirectAfterRegistrationSubscriber:
    arguments: ['@fos_user.mailer', '@fos_user.util.token_generator', '@router']
    tags:
        - { name: kernel.event_subscriber }

通过自动装配和自动配置,你甚至可以sypmlify到:

AppBundle\EventListener\RedirectAfterRegistrationSubscriber:
    arguments:
        $mailer: '@fos_user.mailer'