2017-04-12 43 views
0

我有一個Slim 3路由:$app->get('/calendar/{date}', 'CalendarCtrl:getSchedule');
此路由可以通過簡單的HTML列表,json或xml格式返回相同的時間表。
現在我正在尋找一個基於Accept(或更多標頭)HTTP標頭的簡單REST解決方案。基於標頭的Slim 3路由

例如:
請求:

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

響應:

Content-Type: application/json 
Body: {json schedule} 

所以路線應該是水木清華這樣的:$app->get('/calendar/{date}', {Accept: application/json}, 'CalendarCtrl:getScheduleJson');

我知道我可以檢查該頭在一個路由處理器。但我正在尋找一個簡單的聲明式解決方案。

回答

1

從您的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 
}  
}); 
+0

感謝中間件想法之前添加一箇中間件來檢查該頭。對我來說這是一個新概念,你能告訴我什麼使用中間件的最佳實踐在Slim中?您使用了匿名函數,Slim文檔使用可調用的類,其他指南擴展了SlimMiddleware(Slim 2)。您將什麼用作中間件的最佳實踐?謝謝 – Doc999tor

+0

還有一個問題:在Accept:text/html標頭的情況下,我需要使用Twig模板渲染來構建一個html頁面。它比簡單的'return $ response-> withHeader('Content-type','application/json')稍微複雜一些;問題是:這樣的邏輯應該放在中間件中嗎?也許控制器是正確的地方?如果是這樣,我回到前面的問題:中間件不解決基於頭的路由問題。這根本不是路由。 – Doc999tor

+0

Slim中的中間件很簡單,你會在你的API周圍提供一個圖層在將請求傳遞給API之前檢查一些東西,並在發送給客戶端之前在響應中添加一些東西 –