Ginger Ginger - 4 years ago 155
PHP Question

How is the ID Converted to A Task?

I am trying to understand this Symfony code:

https://github.com/lyrixx/SFLive-Paris2016-Workflow/blob/master/src/AppBundle/Controller/TaskController.php

In particular:

/**
* @Route("/show/{id}", name="task_show")
*/
public function showAction(Task $task)
{
return $this->render('task/show.html.twig', [
'task' => $task,
]);
}


How does Symfony need to know that the {id} in the Route should get converted to the $task in showAction(Task $task)?

Answer Source

Symfony uses parameter converters under the hood. Their use is optional with the @ParamConverter annotation, but implicit when the method is type-hinted as in your example. One could rewrite your example using an explicit call as:

/**
 * @Route("/show/{id}", name="task_show")
 * @ParamConverter("task", "AppBundle\Entity\Task:Task")
 */
public function showAction($task)

This functionality is based around the objects being Doctrine models, as documented in the controllers section of the Symfony manual:

Normally, you'd expect a $id argument to showAction(). Instead, by creating a new argument ($post) and type-hinting it with the Post class (which is a Doctrine entity), the ParamConverter automatically queries for an object whose $id property matches the {id} value. It will also show a 404 page if no Post can be found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download