Symfony2 Get Your Parameter’s On Board Too Like A Boss :) Or Maybe A Newbie :'( ?

Let’s get to the point, and tell me which notation you like/need. This one:

    /**
     * @Route("/handle-zipcode", name="handle_zipcode")
     * @Method("GET|POST")
     */
    public function handleZipcodeAction(Request $request)
    {
        $zipCode = $request->get('zipCode');
        $someOther = $request->get('someOther');
 
        // some more usage of the vars above
    }

Or this other:

    /**
     * @Route("/handle-zipcode", name="handle_zipcode", defaults={"PostalCode" = 0, "zipCode" = 0, "someOther" = 0})
     * @Method("GET|POST")
     * @ParamConverter("zipCode", options={"name": "PostalCode"})
     * @ParamConverter("someOther")
     */
    public function handleZipcodeAction($zipCode, $someOther)
    {
        // you can use $zipcode and $someOther freely
    }

I was trying to come up with a refactor that would clean these assignments from my controller actions. So I wrote a Converter:

<?php
 
namespace Cordova\Bundle\MainBundle\Util;
 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
 
class RequestParamConverter implements ParamConverterInterface
{
    public function apply(Request $request, ConfigurationInterface $configuration)
    {
        $param = $configuration->getName();
 
        if (!$request->attributes->has($param)) {
            return false;
        }
 
        $options = $configuration->getOptions();
 
        if (isset($options['name'])) {
            $value = (int) $request->get($options['name']);
        } else {
            $value = (int) $request->get($param);
        }
 
        $request->attributes->set($param, $value);
 
        return true;
    }
 
    public function supports(ConfigurationInterface $configuration)
    {
        if (null === $configuration->getClass()) {
            return true;
        }
 
        return false;
    }
}

And configured it on my services.xml like:

<parameters>
        <parameter key="cordova_main.example.class">Cordova\Bundle\MainBundle\Util\RequestParamConverter</parameter>
    </parameters>
 
    <services>
        <service id="cordoval_parameter_converter" class="%cordova_main.example.class%">
            <tag name="request.param_converter" priority="-2" />
        </service>
    </services>

I want to thank the Lord Jesus Christ for this totally undeserved opportunity to enjoy and share this experimentation with code.

Encouragements in all good!

Oh and don’t forget to check this blog post http://www.craftitonline.com/2012/11/lazy-load-services-and-do-not-inject-the-container-into-them/ !

Leave a Reply

Your email address will not be published. Required fields are marked *