Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : Automatically map query string in Controller parameter

Tags:

symfony

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

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

But I want to use query string instead eg: http://a.com/test?name=foo

How to do that ? For me there are only 3 solutions:

  • re-implement ControllerResolverInterface
  • use a custom ParamConverter
  • $name = $request->query->get('name');

Is there another solution ?

like image 773
Remy Mellet Avatar asked Dec 24 '22 12:12

Remy Mellet


1 Answers

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:
  querystring_paramconverter:
    class: AppBundle\Extension\QueryStringConverter
    tags:
      - { name: request.param_converter, converter: querystring }

In your controller:

/**
 * @Route("/test")
 * @ParamConverter("name", converter="querystring")
 */
public function action(Request $request, $name) {
  return new Response(print_r($name, true));
}
like image 92
Remy Mellet Avatar answered Dec 27 '22 21:12

Remy Mellet