Conversion of parameters with Symfony2

1

Does anyone know of any elegant way to convert a parameter in symfony2 I know there is the ParamConverter Symfony2 but I do not use annotations. Any alternative?

    
asked by anonymous 18.08.2014 / 19:10

1 answer

1

It is not necessary to use annotations for ParamConverter , contrary to what I said before.

First you need to create a class that implements the ParamConverterInterface interface, as shown below:

namespace Acme\Bundle\DemoBundle\Request\ParamConverter;

use Acme\Bundle\DemoBundle\Entity\Teste;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;

class TesteParamConverter implements ParamConverterInterface
{
    public function apply(Request $request, ParamConverter $configuration)
    {
        $param = $configuration->getName();
        $request->attributes->set($param, new Teste());

        return true;
    }

    public function supports(ParamConverter $configuration)
    {
        return ("Acme\Bundle\DemoBundle\Entity\Teste" === $configuration->getClass());
    }
} 

Then, register this ParamConverter in the services of your application with the tag request.param_converter :

parameters:
    acme.request.param_converter.teste_param_converter.class: Acme\Bundle\DemoBundle\Request\ParamConverter\TesteParamConverter

services:
    acme.request.param_converter.teste:
        class: %acme.request.param_converter.teste_param_converter.class%
        tags:
            - { name: request.param_converter }

Finally, you need to define what you will receive in action via your ParamConverter . In my case I created an entity Teste just for the purpose of the answer, even:

namespace Acme\Bundle\DemoBundle\Entity;

class Teste
{
}

I hope I have helped! :)

    
18.08.2014 / 20:40