代码之家  ›  专栏  ›  技术社区  ›  yevg

在Symfony PHP中重定向来自事件订阅服务器的响应

  •  0
  • yevg  · 技术社区  · 7 年前

    我的订户如下:

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    use Symfony\Component\HttpKernel\KernelEvents;
    
    use Symfony\Component\HttpFoundation\RedirectResponse;
    
    class KernelSubscriber implements EventSubscriberInterface {
    
        public function __construct() {
    
            // some stuff here but not relevant for this example
        }
    
        public static function getSubscribedEvents(): array {
    
            return [ KernelEvents::REQUEST => 'onRequest' ];
        }
    
        public function onRequest(GetResponseEvent $event): void {
    
            // if conditions met
            //     301 redirect to some internal or external URL
    
            if(!$event->isMasterRequest()) return;
        }   
    }
    

    如果这是一个控制器,我会返回 $this->redirectToRoute('route') 或者类似的,但是从 onRequest

    如何从该事件订阅服务器返回响应(特别是重定向)?

    1 回复  |  直到 7 年前
        1
  •  12
  •   Alex.Barylski    7 年前

    应该是这样的:

    $event->setResponse(new RedirectResponse($route));
    
    推荐文章