我在Silex中有一个项目,使用标准定义的路由,但是对于不存在的路由,我想重新路由或转发到主页或错误页面。
我没有在文档中看到此信息,但是我看不到为什么这不可能。
我该怎么做呢?
最佳答案
从error handler复制Silex Skeleton,您可以轻松做到:
<?php
$app->error(function (\Exception $e, Request $request, $code) use ($app) {
if ($app['debug']) {
return;
}
// 404.html, or 40x.html, or 4xx.html, or error.html
$templates = array(
'errors/'.$code.'.html',
'errors/'.substr($code, 0, 2).'x.html',
'errors/'.substr($code, 0, 1).'xx.html',
'errors/default.html',
);
return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
});
或者,您可能想重定向/转发(前者进行浏览器往返,而后者则不需要)。检查文档中的redirect / forward,基本上不需要返回基于渲染模板的响应,而只需要
return $app->redirect
或return $app->forward
关于php - 不存在的路由的后备路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28591916/