kee*_*tdk 4 symfony doctrine-orm fosrestbundle symfony-2.2 symfony-2.3
使用Symfony2,FOSRest和Doctrine构建API.鉴于以下路线:
"GET /api/path/to/product"
Run Code Online (Sandbox Code Playgroud)
以及以下参数:
[("vendorID", 10), ("destination", "tanzania"), ("type", "accommodation"), ("sort", "price", "ASC")]
Run Code Online (Sandbox Code Playgroud)
使用FOSRest捆绑包可以检索这些字符串,但是,将它们映射到学说查询是挑战的起因.
我想过使用为查询字符串的不同组合定制的大量案例语句,而不是优雅的解决方案.想要构建一个不会严重影响性能的更通用的控制器.任何建议都会有帮助.
FOSRestBundle有一个非常酷的param fetcher 监听器.有了它,您可以使用注释定义查询字符串参数,允许它们是否可为空,设置默认值,定义要求.根据您的示例参数,我猜到了一些值
/**
* @QueryParam(name="vendorID", requirements="\d+", strict=true, description="vendor id")
* @QueryParam(name="destination", nullable=true, description="restrict search to given destination")
* @QueryParam(name="type", nullable=true, description="restrict search to given type")
* @QueryParam(name="sort", requirements="(price|foo|bar)", default="price", description="sort search according to price, foo or bar")
* @QueryParam(name="dir", requirements="(ASC|DESC)", default="ASC", description="sort search ascending or descending")
*/
public function getProducts(ParamFetcher $paramFetcher)
{
$vendorID = $paramFetcher->get('vendorID');
// and so on
}
Run Code Online (Sandbox Code Playgroud)
对于构建查询构建器,使用具有默认值的params非常简单,因为它们永远不会填充未定义的值.对于严格的参数,它也没有问题,因为400 Bad Request如果它缺失或不符合要求,严格的参数将会提出.只有使用可为空的params,在将条件添加到查询构建器之前,必须检查not null.
顺便说一句.看看NelmioApiDocBundle,它为每个带有@ApiDoc漂亮文档注释的动作生成.它还解析了param fetcher注释.非常便利.