Overriding Default FOSUserBundle Controller in Symfony 3.4

大城市里の小女人 提交于 2019-12-24 00:59:59

问题


I'm using the Fosuserbundle to manager members in my project { SF::3.4.8 }, when trying to override the controller of the registrationController by following the Symfony documentation

<?php

namespace TestUserBundle;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOSUserBundle\Controller\RegistrationController as BaseController;

class RegistrationController extends BaseController {

    public function registerAction(Request $request)
    {
        die("Hello");
    }
}

but the system ignore that controller and still use The original controller, so if there any way to override my controller by


回答1:


First, overriding the controller is probably not the best way to process. You should consider to hook into controller. Here is the related documentation: https://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html

Then if you still want to override the controller, you should act in the dependency injection. The service name of the controller is fos_user.registration.controller.

To replace the service you can simply use:

services:
    fos_user.registration.controller: 
        class: YourController
        arguments:
            $eventDispatcher: '@event_dispatcher'
            $formFactory: '@fos_user.registration.form.factory'
            $userManager: '@fos_user.user_manager'
            $tokenStorage: 'security.token_storage'

You can also override it in a CompilerPass. Which is probably the best solution for you because you do this inside another bundle.

Here is how it should look:

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class ReplaceRegistrationController extends CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $container
            ->getDefinition('fos_user.registration.controller')
            ->setClass(YourController::class)
        ;
    }
}

Don't forget to register it inside your bundle:

$container->addCompilerPass(new ReplaceRegistrationController());


来源:https://stackoverflow.com/questions/49917021/overriding-default-fosuserbundle-controller-in-symfony-3-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!