Frameman
Frameman

Reputation: 111

Overriding Default FOSUserBundle Controller in Symfony 3.4

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

Upvotes: 3

Views: 1810

Answers (1)

Nek
Nek

Reputation: 3105

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

Upvotes: 1

Related Questions