在 Symfony 中路由有很多可选参数
Route with a lot of optional parameters in Symfony
我得到了很多产品,可以用很多不同的参数进行筛选。
所以用户在表单中输入搜索参数,然后列表根据这些参数进行过滤。
我尝试创建这样的路线:
/**
* Display a list of product
* @Route("/product/list/{name}/{price_min}/{price_max}/{publish_date}/{supplier_code}", name="product_list")
*/
public function listProduct(){
// ... Check parameters format and then escape special caracters
// ... Display product logic
return $this->render('Product/product_list.html.twig', $array_params_view);
}
我知道你可以提供 optional parameter,但这个解决方案对我来说真的很糟糕......
我认为可能还有其他解决方案。
我曾考虑使用 Request 而不是大量参数,但如果我这样做,我会失去漂亮且易于阅读的功能 URL,也许它会是更难管理路由。
我不知道搜索功能的最佳解决方案是什么。
如果您使用路由搜索列表,我认为您需要阅读此内容:link
查询字符串是一种更好的搜索方式。
// the query string is '?foo=bar'
$request->query->get('foo');
// returns 'bar'
/**
* Display a list of product
*
* @Route("/list/", name="product_list")
*
* @param Request $request
*
*/
public function listProduct(Request $request)
{
$name = $request->query->get('name');
$price_min = $request->query->get('price_min');
$price_max = $request->query->get('price_max');
$publish_date = $request->query->get('publish_date');
$supplier_code = $request->query->get('supplier_code');
$list_products = $this->getListProducts($name,$price_min,$price_max,$publish_date,$supplier_code);
//Next code
......
}
您只需在 getListProducts 函数中进行控制
或者不管你怎么称呼它,参数可以作为 null
到达
我得到了很多产品,可以用很多不同的参数进行筛选。 所以用户在表单中输入搜索参数,然后列表根据这些参数进行过滤。
我尝试创建这样的路线:
/**
* Display a list of product
* @Route("/product/list/{name}/{price_min}/{price_max}/{publish_date}/{supplier_code}", name="product_list")
*/
public function listProduct(){
// ... Check parameters format and then escape special caracters
// ... Display product logic
return $this->render('Product/product_list.html.twig', $array_params_view);
}
我知道你可以提供 optional parameter,但这个解决方案对我来说真的很糟糕...... 我认为可能还有其他解决方案。
我曾考虑使用 Request 而不是大量参数,但如果我这样做,我会失去漂亮且易于阅读的功能 URL,也许它会是更难管理路由。
我不知道搜索功能的最佳解决方案是什么。
如果您使用路由搜索列表,我认为您需要阅读此内容:link
查询字符串是一种更好的搜索方式。
// the query string is '?foo=bar'
$request->query->get('foo');
// returns 'bar'
/**
* Display a list of product
*
* @Route("/list/", name="product_list")
*
* @param Request $request
*
*/
public function listProduct(Request $request)
{
$name = $request->query->get('name');
$price_min = $request->query->get('price_min');
$price_max = $request->query->get('price_max');
$publish_date = $request->query->get('publish_date');
$supplier_code = $request->query->get('supplier_code');
$list_products = $this->getListProducts($name,$price_min,$price_max,$publish_date,$supplier_code);
//Next code
......
}
您只需在 getListProducts 函数中进行控制 或者不管你怎么称呼它,参数可以作为 null
到达