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 use redirect in constructors. Constructor return only current object of the class
(object of controller in your case), and it can't return redirect object
. Maybe you can solve your task in route, using FrameworkBundle:Redirect:urlRedirect
:
# redirecting the root
root:
path: /
defaults:
_controller: FrameworkBundle:Redirect:urlRedirect
path: /app
permanent: true
Check examples in How to Configure a Redirect without a Custom Controller
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?