I want to do a redirect in the constructor in a specific sutiation. I tried to do it like this:
return new \\Symfony\\Component\\HttpFoundation\\RedirectResponse
Bad idea to redirect from controller directly. I would rather throw some custom exception.
class FooController{
public function __construct(){
if ( some_test ){
throw RedirectionException(); // name it however you like
}
}
}
Then, in Symfony, setup the ExceptionListener which will evaluate class-type of Exception thrown and redirect you application to another URL, if necessary. This service will most likely depend on @routing service to generate alternate URL destination.
Service config:
services:
kernel.listener.your_listener_name:
class: Your\Namespace\AcmeExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
Listener class:
class AcmeExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
if ( $exception instanceof RedirectionException ){
$response = new RedirectResponse();
$event->setResponse($response);
}
}
}
This way to can maintain single error handling and redirection logic. Too complicated?