Built an API using Symfony2, FOSRest and Doctrine. Given the following route:
"GET /api/path/to/product"
And the following parameters:
[("vendorID", 10), ("destination", "tanzania"), ("type", "accommodation"), ("sort", "price", "ASC")]
Using FOSRest bundle its possible to retrieve these strings, however, mapping them to doctrine queries is where the challenge arises.
I thought about using numerous case statements customised for the different combinations of query strings, not an elegant solution. Would like to build a more generic controller that won't severely affect performance. Any advice will help.
The FOSRestBundle has a very cool param fetcher listener. With it you can define your query string parameters with annotations, allow them nullable or not, set default values, define requirements. Based on your example parameters I guessed some values
/**
* @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
}
For building the query builder, it's very simple with the params which have a default value, as they will never get filled with an undefined value. For strict params it is also no problem, as a strict param will raise a 400 Bad Request
if it's missing or does not fit the requirements. Only with nullable params you have to check against not null before you add the conditions to the query builder.
Btw. take a look on the NelmioApiDocBundle, which generates for every action annotated with @ApiDoc
a nice documentation. It parses also the param fetcher annotations. Very handy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With