Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting Doctrine Entity into Symfony controller based on route parameters

I want to inject Doctrine entities into controller actions based on the route parameters in an attempt to reduce the insane amount of code duplication inside my controllers.

For example I have the following route

product:
    path:     /product/edit/{productId}
    defaults: { _controller: ExampleBundle:Product:edit }

Instead of my current approach

public function editAction($productId)
{
    $manager = $this->getDoctrine()->getManager();
    $product = $manager->getRepository('ExampleBundle:Product')
        ->findOneByProductId($productId);

    if (!$product) {
        $this->addFlash('error', 'Selected product does not exist');
        return $this->redirect($this->generateUrl('products'));
    }

    // ...
}

I'd like this to be handled else where as it's repeated in at least 6 controller actions currently. So it would be more along the lines of

public function editAction(Product $product)
{
    // ...
}

It seems this has in fact been done before and the best example I can find is done by the SensioFrameworkBundle http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html

I'd use this but were not using annotations in our Symfony projects so need to look at alternatives. Any suggestions on how this can be achieved?

like image 945
Nick Avatar asked Jan 25 '26 21:01

Nick


1 Answers

If you read the docs carefully, you'll learn that param converters actually work without annotations:

To detect which converter is run on a parameter the following process is run:

  • If an explicit converter choice was made with @ParamConverter(converter="name") the converter with the given name is chosen.
  • Otherwise all registered parameter converters are iterated by priority. The supports() method is invoked to check if a param converter can convert the request into the required parameter. If it returns true the param converter is invoked.

In other words if you don't specify a param converter in an annotation, Symfony will iterate through all registered converters and find the most appropriate one to handle your argument (based on a type hint).

I prefer to put an annotation in order to:

  • be explicit
  • save some processing time
like image 120
Jakub Zalas Avatar answered Jan 28 '26 14:01

Jakub Zalas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!