Silex 在匹配回调中触发 404 错误
Silex trigger 404 error inside match callback
我有这段代码,匹配来自 json 文件的一些路由:
$this->app->match($routePattern, function(Request $request, \Silex\Application $app) use($routeIdent, $templateConfig) {
//now here i need to check some conditions and,
//in case, trigger 404 error, but without redirect!!!!
if($templateConfig['test'] === true){
//----> TRIGGER 404
}
});
有办法处理吗?
我不确定我是否正确理解了你的问题。你if你想在if中实现404处理吗?一种解决方案是在此处返回响应。例如。如果你使用 Symfony\Component\HttpFoundation\Response 对象和内置的树枝服务,你可以这样做:
use Symfony\Component\HttpFoundation\Response
$this->app->match($routePattern, function(Request $request, \Silex\Application $app) use($routeIdent, $templateConfig) {
if($templateConfig['test'] === true){
//----> TRIGGER 404
return new Response( $app['twig']->render('404.html.twig'), 404);
}
})
希望这就是您要找的。
您可以使用 abort()
:
return $app->abort(404);
return 不是必需的,因为它会抛出,我只是更喜欢将它用作一种发出信号作为退出点的方式。
我有这段代码,匹配来自 json 文件的一些路由:
$this->app->match($routePattern, function(Request $request, \Silex\Application $app) use($routeIdent, $templateConfig) {
//now here i need to check some conditions and,
//in case, trigger 404 error, but without redirect!!!!
if($templateConfig['test'] === true){
//----> TRIGGER 404
}
});
有办法处理吗?
我不确定我是否正确理解了你的问题。你if你想在if中实现404处理吗?一种解决方案是在此处返回响应。例如。如果你使用 Symfony\Component\HttpFoundation\Response 对象和内置的树枝服务,你可以这样做:
use Symfony\Component\HttpFoundation\Response
$this->app->match($routePattern, function(Request $request, \Silex\Application $app) use($routeIdent, $templateConfig) {
if($templateConfig['test'] === true){
//----> TRIGGER 404
return new Response( $app['twig']->render('404.html.twig'), 404);
}
})
希望这就是您要找的。
您可以使用 abort()
:
return $app->abort(404);
return 不是必需的,因为它会抛出,我只是更喜欢将它用作一种发出信号作为退出点的方式。