Cannot autowire service FOSUserBundle, Symfony 3.4

2020-07-11 10:01发布

问题:

I'm trying to override the registration controller of my FOSUserBundle. I've followed the steps on https://symfony.com/doc/3.4/bundles/inheritance.html But I get the following error:

Cannot autowire service "AppBundle\Controller\RegistrationController": argument "$formFactory" of method "FOS\UserBundle\Controller\RegistrationController::__construct()" references interface "FOS\UserBundle\Form\Factory\FactoryInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "fos_user.profile.form.factory", "fos_user.registration.form.factory", "fos_user.change_password.form.factory", "fos_user.resetting.form.factory".

My RegistrationController.php :

// src/UserBundle/Controller/RegistrationController.php
namespace AppBundle\Controller;

use FOS\UserBundle\Controller\RegistrationController as BaseController;
use Symfony\Component\HttpFoundation\Request;

    class RegistrationController extends BaseController
    {
        public function registerAction(Request $request)
        {
            $response = parent::registerAction($request);

            // ... do custom stuff
            return $response;
        }
     }

My AppBundle.php

<?php

namespace AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AppBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}

If more information is needed tell me so I can update this question.

回答1:

I installed and configured a fresh copy of Symfony 3.4 along with the latest FOSUserBundle 2.1

Since bundle inheritance is going away, just adjust the register route to point to your controller:

# config/routes.yaml
fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

fos_user_registration_register:
    path: /register
    controller: AppBundle\Controller\RegistrationController::registerAction

And then inject the form factory into your controller:

# app/services.yaml, keep all the standard defaults above
AppBundle\Controller\RegistrationController:
    arguments:
        $formFactory: '@fos_user.registration.form.factory'

And you should be good to go.

The only remaining question is why you would want to do this in the first place? You would basically need to copy/paste the entire registerAction from your base class. Most of the time you would want to create an FOS event subscriber and listen for REGISTRATION_INITIALIZE, REGISTRATION_SUCCESS,REGISTRATION_COMPLETED or REGISTRATION_FAILURE events.



回答2:

I know for sure, that this works for Symfony 3.2.3 This is only for symfony version <= 3. Because bundle inheritence is depraceted and will be disabled in 4. Change the version of FOSUserBundle in the composer.json to

"friendsofsymfony/user-bundle": "2.0.2"

and run command to update it

composer update