Conversion of parameters with Symfony2

Asked

Viewed 42 times

1

Does anyone know any elegant way to convert a parameter to symfony2 Paramconverter Symfony2 but I don’t use Annotations. Some alternative ?

  • As far as I know, Paramconverter is the only way to convert parameters into objects. Personally, I love to use Annotations because I put practically all the information concerning a certain action in the Annotations.

  • Good Annotations in my case kills all inheritances of controllers that I have, and generates a high level of coupling between configurations and classes which is horrible for the reuse of classes since it is tied to a configuration made by Annotation. Each case is a case, in my Annotations do not meet me. I’m thinking of making a Bundle for this since I can not find anything =S

  • Solved, I will add an answer :)

1 answer

1


It is not necessary to use Annotations for the ParamConverter, contrary to what I had said before.

First you need to create a class that implements the interface ParamConverterInterface, according to the code 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 record this one 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 on action through his ParamConverter. In my case I created an entity Teste only for the purpose of the answer, even:

namespace Acme\Bundle\DemoBundle\Entity;

class Teste
{
}

I hope I’ve helped! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.