Symfony ParamConverter: the best friend you don’t know yet

Thomas BERTRAND
2 min readAug 30, 2022

--

Photo by José Martín Ramírez Carrasco on Unsplash

Symfony framework is an awesome tool to create web applications, API… Its documentation is pretty well written but really big and there are some hidden gems that we really need to talk about!

One of the most common features to implement when you are creating any website is getting data from the database. With Symfony it is pretty simple: you implement a controller that will call the database via a repository to find the data you are looking for.

Let see how we can do this.

The standard way

To summarize

  • You call a route with an ID
  • The ID is used by the repository to try to find the product by its ID (the ORM do its job and return a proper product entity)
  • If the product has not been found your return a 404 error
  • Otherwise you return the product

Doing all these steps with the code above is certainly the best way to understand how Symfony works. Indeed every step is easy to identify.

Sadly, this particular code will become pretty redundant between all the functions of your controllers.

But deeper in the documentation there is an awesome feature that will handle all the process for you!

The ParamConverter

This element is a part of the awesome SensioFrameworkExtraBundle.
Its goal is simple: trying to find automatically an element by its ID and return a 404 if no element has been found.

That means you can now focus on your business code rather than implementing the same technical again and again!

The converter tries to get a Product entity from the request attributes available in the Route annotation (here id).
It implies the name of the parameter must be the same in the entity otherwise we would have to explain the ParamConverter what is the name of the variable it is looking for.

Multiple ParamConverters

Sometimes you need to use multiple parameter in a route and still want to find the entities via the ParamConverter.

To do so, simply add the annotation ParamConverter to explain to the ParamConverter which variable should be used to find the entity

Here for the product variable we will find it via its ID and the ID value is available in product_id parameter.

Going further

We saw the most important part of the ParamConverter but it is a tons of other possibilities.

To know more about ParamConverter come check the Symfony documentation.

https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html

--

--