4
votes

I have a catch-all fallback route in Symfony2 that I couldn't get to work in Symfony3. I tried this exact syntax (a verbatim copy of my Symfony2 route) and that didn't work.

fallback:
    path:     /{req}
    defaults: { _controller: MyBundle:Default:catchAll }
    requirements:
        req: ".+"

How can I get this working in Symfony3? (It's literally the only thing holding me back from using Symfony3 and keeping me at v2.8)

3

3 Answers

14
votes

This should help you:

route1:
  path: /{req}
  defaults: { _controller: 'AppBundle:Default:index' }
  requirements:
      req: ".+"

Where, my controller is called "DefaultController", and I have a function called "indexAction()".

Here is my code for the DefaultController:

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
...

I actually did try what you said in my environment, and it didn't work until I had the right controller settings specified.


EDIT:

For this to work, it was necessary to add the parameter Request $request (with the type hint) to the action's method signature.

5
votes

I found the current accepted answer almost useful for Symfony 4, so I'm going to add my solution:


This is what I did to get it working in Symfony 4:

  • Open /src/Controller/DefaultController.php, make sure there is a function called index(){}
    • It's not required to add the Request $request as first param as some comment suggest.
    • This is the method that will handle all urls caught by the routes.yaml
  • Open /config/routes.yaml, add this:

    yourRouteNameHere:
      path: /{req}
      defaults: { _controller: 'App\Controller\DefaultController::index' }
      requirements:        #  the controller --^     the method --^
        req: ".*"`  # not ".+"
    
1
votes

You can also override Exception controller.

# app/config/config.yml
twig:
    exception_controller:  app.exception_controller:showAction

# app/config/services.yml
services:
    app.exception_controller:
        class: AppBundle\Controller\ExceptionController
        arguments: ['@twig', '%kernel.debug%']
namespace AppBundle\Controller;

use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ExceptionController
{
    protected $twig;

    protected $debug;

    public function __construct(\Twig_Environment $twig, $debug)
    {
        $this->twig = $twig;
        $this->debug = $debug;
    }

    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        // some action

        return new Response($this->twig->render('error/template.html.twig', [
                'status_code' => $exception->getStatusCode()
            ]
        ));
    }
}