Symfony2:自动映射控制器参数中的查询字符串 [英] Symfony2 : Automatically map query string in Controller parameter
本文介绍了Symfony2:自动映射控制器参数中的查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Symfony2 中,路由参数可以自动映射到控制器参数,例如:http://a.com/test/foo 将返回foo"
In Symfony2, the route parameters can be automatically map to the controller arguments, eg: http://a.com/test/foo will return "foo"
/**
* @Route("/test/{name}")
*/
public function action(Request $request, $name) {
return new Response(print_r($name, true));
}
见 http://symfony.com/doc/current/book/routing.html#route-parameters-and-controller-arguments
但我想使用查询字符串代替例如:http://a.com/test?name=foo
怎么做?对我来说只有 3 个解决方案:
How to do that ? For me there are only 3 solutions:
- 重新实现ControllerResolverInterface
- 使用自定义 ParamConverter
- $name = $request->query->get('name');
还有其他解决方案吗?
推荐答案
我为那些想要使用转换器的人提供代码:
I provide you the code for those which want to use a converter :
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Put specific attribute parameter to query parameters
*/
class QueryStringConverter implements ParamConverterInterface{
public function supports(ParamConverter $configuration) {
return 'querystring' == $configuration->getConverter();
}
public function apply(Request $request, ParamConverter $configuration) {
$param = $configuration->getName();
if (!$request->query->has($param)) {
return false;
}
$value = $request->query->get($param);
$request->attributes->set($param, $value);
}
}
services.yml :
services.yml :
services:
querystring_paramconverter:
class: AppBundle\Extension\QueryStringConverter
tags:
- { name: request.param_converter, converter: querystring }
在您的控制器中:
/**
* @Route("/test")
* @ParamConverter("name", converter="querystring")
*/
public function action(Request $request, $name) {
return new Response(print_r($name, true));
}
这篇关于Symfony2:自动映射控制器参数中的查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文