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

时间:2019-02-24 20:34:46

标签: symfony 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".

1 个答案:

答案 0 :(得分:2)

我想您正在使用服务的自动发现。像这样:

# services.yaml

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

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

解决方案:

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

借助自动装配和自动配置,您甚至可以将其语法化为:

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