Handling query strings?

Built API using Symfony2, FOSRest and Doctrine. Given the following route:

"GET /api/path/to/product" 

And the following options:

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

Using the FOSRest package, you can get it to get these lines, however, matching them with doctrine requests is where the problem arises.

I was thinking about using numerous case statements tuned for different combinations of query strings, rather than an elegant solution. I would like to build a more general controller that will not greatly affect performance. Any advice would help.

+4
source share
1 answer

FOSRestBundle has a very cool fetcher parameter listener . With it, you can define query string parameters using annotations, allow them to be reset or not, set default values, define requirements. Based on your example parameters, I figured out 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 } 

To build a query builder, it is very simple with parameters that have a default value, since they will never be filled with an undefined value. For strict parameters, this is also not a problem, since a strict parameter will raise 400 Bad Request if it is missing or does not meet the requirements. Only with null parameters should you check non-null before adding conditions to the query builder.

Btw. look at the NelmioApiDocBundle , which generates good documentation for every action annotated with @ApiDoc . It also analyzes fetcher parameter annotations. Very comfortably.

+7
source

Source: https://habr.com/ru/post/1489082/


All Articles