Controllers and Routing¶
Creating Controller¶
To generate controllers, you should use the Maker bundle:
./bin/console make:controller
Note
Note you must have already configured Maker Bundle
Configuring Routing¶
To configure Routing, you should use annotations
Your annotations should define the "magic string" values for each option.
Your controller should only have one action, though it is acceptable to have minor related actions such as a redirect in the same controller.
Your controller should contain no business logic, only glue code that uses services to handle business logic
Your controller should generally not handle exceptions, instead this should be handled globally using an EventListener
For example:
<?php
final class MyController extends AbstractController
{
/**
* @var BusinessLogic
*/
private $businessLogic;
public function __construct(BusinessLogic $businessLogic)
{
$this->businessLogic = $businessLogic;
}
/**
* @Route("/my-action-redirect", name="my_action_redirect")
*/
public function redirectToMyAction(): RedirectResponse
{
return $this->redirectToRoute('my_action');
}
/**
* @Route("/my-action", name="my_action")
*/
public function action(): JsonResponse
{
return new JsonResponse($this->businessLogic->getJsonString(), Response::HTTP_OK, [], true);
}
}
Using Routes¶
You should always use the functions:
- \Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate
- \Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait::generateUrl
- \Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait::redirectToRoute
To generate URLs, you should never write or create URLs are hard coded "magic strings"
see https://symfony.com/doc/current/routing.html#generating-urls