Symfony2:在Controller参数中自动映射查询字符串

Rem*_*let 3 symfony

在Symfony2中,路由参数可以自动映射到控制器参数,例如:http://a.com/test/foo将返回"foo"

    /**
     * @Route("/test/{name}")
     */
    public function action(Request $request, $name) {
        return new Response(print_r($name, true));
    }
Run Code Online (Sandbox Code Playgroud)

请参阅http://symfony.com/doc/current/book/routing.html#route-parameters-and-controller-arguments

但我想使用查询字符串,例如:http://a.com/test ?name = foo

怎么做 ?对我来说,只有3个解决方案:

还有其他解决方案吗?

Rem*_*let 7

我为你提供了想要使用转换器的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

services.yml:

services:
  querystring_paramconverter:
    class: AppBundle\Extension\QueryStringConverter
    tags:
      - { name: request.param_converter, converter: querystring }
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

/**
 * @Route("/test")
 * @ParamConverter("name", converter="querystring")
 */
public function action(Request $request, $name) {
  return new Response(print_r($name, true));
}
Run Code Online (Sandbox Code Playgroud)