今天写了一个地址跳转的EventSubscriber;
部分代码:
/**
* Request access check.
*
* @param \Symfony\Component\HttpKernel\Event\KernelEvent $event
* RequestEvent event.
*/
public function checkForRedirection(KernelEvent $event) {
$current_path = \Drupal::service('path.current')->getPath();
$alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
if ($alias == '/zh-hant/xx') {
$url = '/zh-hans/xx1';
}
elseif ($alias == '/zh-hant/xxa') {
$url = '/zh-hans/xxb';
}
if (isset($url)) {
$response = new RedirectResponse($url);
return $response->send();
}
}
测试的时候发现第一次访问可以实现跳转,但是第二次就直接not found;但是清除缓存之后就好了。以为是路有缓存的原因。
最后发现跳转的时候应该使用
e
v
e
n
t
来
做
,
而
不
是
event来做,而不是
event来做,而不是response.
这样写就没有问题了:
if (isset($url)) {
$response = new RedirectResponse($url, 302);
$event->setResponse($response);
}