Symfony and named ParamConverters

Symfony’s ParamConverter is a common way to transform some GET param to an entity before your controllers action.
This happens most of the time via type hinting and priority detection kinda magic in the background.
But as magic is often obscure sometimes you need a bit of explicitness.

F.e. when you have more and different ParamConverter per entity you want to name them explicitly.
Then you can use named ParamConverters.

In the documentation this issue is a bit fragmented, so here is the compact version:

Set the “converter” attribute in the param_converter service tag.
Read it in the documentation:

You can register a converter by priority, by name (attribute “converter”) or both.

<service id="my_converter" class="MyBundle\Request\ParamConverter\MyConverter">
<tag name="request.param_converter" priority="-2" converter="my_converter" />

In you controller annotation call the ParamConverter with the converter attribute.
The Symfony ParamConverter dokumentation explains it like this:
If an explicit converter choice was made with @ParamConverter(converter=”name”) the converter with the given name is chosen.

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
* @ParamConverter("post", converter="my_converter")
public function showAction(Post $post)

Leave a Reply

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