处理查询字符串?

时间:2013-07-01 11:41:02

标签: symfony doctrine-orm symfony-2.2 fosrestbundle symfony-2.3

使用Symfony2,FOSRest和Doctrine构建API。鉴于以下路线:

"GET /api/path/to/product"

以下参数:

[("vendorID", 10), ("destination", "tanzania"), ("type", "accommodation"), ("sort", "price", "ASC")]

使用FOSRest捆绑包可以检索这些字符串,但是,将它们映射到教义查询是挑战出现的地方。

我考虑过使用为查询字符串的不同组合定制的大量案例语句,而不是优雅的解决方案。想要构建一个不会严重影响性能的更通用的控制器。任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:7)

FOSRestBundle非常酷param fetcher listener。有了它,您可以使用注释定义查询字符串参数,允许它们是否可为空,设置默认值,定义要求。基于您的示例参数,我猜到了一些值

/**
 * @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
 }

对于构建查询构建器,使用具有默认值的参数非常简单,因为它们永远不会填充未定义的值。对于严格的参数,它也没有问题,因为严格的参数会在400 Bad Request失去或不符合要求时引发@ApiDoc。只有使用可为空的params,在将条件添加到查询构建器之前,必须检查not null。

顺便说一下。看一下NelmioApiDocBundle,它为每个用{{1}}注释的动作生成一个很好的文档。它还解析了param fetcher注释。非常方便。