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

Redirect response from Event Subscriber in Symfony PHP

我正在尝试 return 来自事件订阅者的永久 (301) 重定向响应挂接到 Synfony 中的内核事件 PHP。

我的订阅者如下:

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;
    }   
}

如果这是一个控制器,我会 return $this->redirectToRoute('route') 或类似的东西,但是 return 来自 onRequest 方法的上下文完全不同。

我如何return 来自该事件订阅者的响应(尤其是重定向)?

应该是这样的:

$event->setResponse(new RedirectResponse($route));