symfony2 redirect in constructor

前端 未结 2 1856
心在旅途
心在旅途 2021-01-24 13:07

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         


        
2条回答
  •  渐次进展
    2021-01-24 14:11

    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?

提交回复
热议问题