我正在尝试从连接到 Synfony PHP 内核事件的事件订阅者返回一个永久 (301) 重定向响应。
我的订阅者如下:
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;
}
}
如果这是一个 Controller ,我会返回
$this->redirectToRoute('route')
或类似的东西,但从 onRequest
返回方法是在一个非常不同的上下文中。如何从该事件订阅者返回响应(特别是重定向)?
最佳答案
应该是这样的:
$event->setResponse(new RedirectResponse($route));
关于php - 在 Symfony PHP 中重定向来自事件订阅者的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53244734/