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

时间:2015-11-29 11:32:37

标签: symfony

在Symfony2中,路由参数可以自动映射到控制器参数,例如:http://a.com/test/foo将返回“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/ 测试?name = foo

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

还有其他解决方案吗?

3 个答案:

答案 0 :(得分: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);
    }
}

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));
}

答案 1 :(得分:2)

基于Remy的答案的改进解决方案,它将参数映射到实体:

<?php
namespace AppBundle\Extension;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter;

/**
 * Put specific attribute parameter to query parameters
 */
class QueryStringConverter extends DoctrineParamConverter {

    protected function getIdentifier(Request $request, $options, $name)
    {
        if ($request->query->has($name)) {
            return $request->query->get($name);
        }

        return false;
    }

}

services.yml:

services:
  querystring_paramconverter:
    class: MBS\AppBundle\Extension\QueryStringConverter
    arguments: ['@doctrine']
    tags:
      - { name: request.param_converter, converter: querystring }

在您的控制器中:

/**
 * @Route("/test")
 * @ParamConverter("myobject")
 */
public function action(Request $request, AnyEntity $myobject) {
  return new Response(print_r($myobject->getName(), true));
}

答案 2 :(得分:0)

我没有检查过,但似乎FOSRestBundle提供的@QueryParam注释可以做到: http://symfony.com/doc/current/bundles/FOSRestBundle/param_fetcher_listener.html