【发布时间】:2018-11-11 00:24:03
【问题描述】:
我正在尝试从与 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;
}
}
如果这是一个控制器,我会返回 $this->redirectToRoute('route') 或类似的东西,但从 onRequest 方法返回是在一个完全不同的上下文中。
如何从该事件订阅者返回响应(特别是重定向)?
【问题讨论】:
标签: php symfony symfony4 php-7.2