Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用Slim 3的基于标头的路由_Php_Rest_Http_Routing_Slim - Fatal编程技术网

Php 使用Slim 3的基于标头的路由

Php 使用Slim 3的基于标头的路由,php,rest,http,routing,slim,Php,Rest,Http,Routing,Slim,我有一个简单的3条路线:$app->get('/calendar/{date}',CalendarCtrl:getSchedule') 此路由可以通过简单的HTML列表、json或xml格式返回相同的计划。 现在,我正在寻找一个基于HTTP头的简单REST解决方案 例如: 请求: GET /calendar/2017-01-01 Accept: application/json 答复: Content-Type: application/json Body: {json schedule}

我有一个简单的3条路线:
$app->get('/calendar/{date}',CalendarCtrl:getSchedule')
此路由可以通过简单的HTML列表、json或xml格式返回相同的计划。
现在,我正在寻找一个基于HTTP头的简单REST解决方案

例如:
请求:

GET /calendar/2017-01-01  
Accept: application/json
答复:

Content-Type: application/json
Body: {json schedule}
所以路由应该是这样的smth:
$app->get('/calendar/{date}',{Accept:application/json},'CalendarCtrl:getScheduleJson')


我知道我可以在路由处理程序中检查该标头。但我正在寻找一个简单的声明性解决方案。

在从API发送响应之前,添加一个中间件来检查该头文件

$app->add(function ($req, $res, $next) {
//Checking for $req content-type here then send the response with the same one 
//example 
$headerValue= $req->getHeader('Accept');
if($headerValue=='application/json')
{
  $response = $next($req, $res);
    return $response
            ->withHeader('Content-type', 'application/json');
 }
else{

//check for other header here  
}      
});

在从API发送响应之前,添加一个中间件来检查该标头

$app->add(function ($req, $res, $next) {
//Checking for $req content-type here then send the response with the same one 
//example 
$headerValue= $req->getHeader('Accept');
if($headerValue=='application/json')
{
  $response = $next($req, $res);
    return $response
            ->withHeader('Content-type', 'application/json');
 }
else{

//check for other header here  
}      
});

谢谢你的想法。这对我来说是一个新概念,你能告诉我Slim中使用中间件的最佳实践是什么吗?您使用了匿名函数,Slim文档使用可调用类,其他指南扩展了Slim中间件(Slim 2)。您使用什么作为中间产品的最佳实践?谢谢还有一个问题:在Accept:text/html标题的情况下,我需要构建一个带有细枝模板呈现的html页面。它比简单的
return$response->withHeader('Content-type','application/json')稍微复杂一些,但要复杂得多return$response->withHeader('Content-type','application/json')稍微复杂一些,但要复杂得多