2017-02-26 84 views
0

我開始構建支持多種響應格式的RESTful api。我想用Accept標頭來識別請求的響應格式,或者用請求url附加一個文件後綴。Silex寧靜架構中的格式後綴

E.g. /api/endpoint與包括Accept: application/json*/api/endpoint.json應導致相同的json響應。

/api/endpoint.xml應導致XML響應。

我在Silex中沒有找到任何有關響應格式的文檔,所以如何開始並且還可以允許文件後綴用於格式識別?

感謝, 帕特里克

+0

恐怕你必須在控制器中做這個邏輯...... – martin

回答

0

Silex documentation例子:

use Silex\Application; 
use Silex\Provider\SerializerServiceProvider; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 

$app = new Application(); 

$app->register(new SerializerServiceProvider()); 

// only accept content types supported by the serializer via the assert method. 
$app->get("/pages/{id}.{_format}", function (Request $request, $id) use ($app) { 
// assume a page_repository service exists that returns Page objects. The 
// object returned has getters and setters exposing the state. 
$page = $app['page_repository']->find($id); 
$format = $request->getRequestFormat(); 

if (!$page instanceof Page) { 
    $app->abort("No page found for id: $id"); 
} 

return new Response($app['serializer']->serialize($page, $format), 200, array(
    "Content-Type" => $request->getMimeType($format) 
)); 
})->assert("_format", "xml|json") 
    ->assert("id", "\d+"); 

要獲得默認可以使用類似的東西JSON響應:

$app->get("/pages/{id}{_separator}{_format}", function (Request $request, $id) use ($app) { 
    //... 
})->assert("id", "\d+") 
    ->value("_separator", ".") 
    ->assert("_separator", "\.|\/") 
    ->value("_format", "json") 
    ->assert("_format", "json|xml"); 

// /pages/1 => json reponse 
// /pages/1.json => json response 
// /pages/1.xml => xml response 
// /pages/1/json => json response (as a bonus) 
// and etc. 

另見documentation來配置此行爲全球。