In the shortest terms, routing is about linking the controllers with URLs entered in browser. Todays modern web applications need nice URLs. This means moving away from URLs like /index.php?product_id=23 to something like /catalog/product/t-shirt. This is where routing comes in to play.
Symfony has a powerful routing mechanism that enables us to do the following:
The way routing works in Symfony is that all of the requests come through app.php. Then, the Symfony core asks the router to inspect the request. The router then matches the incoming URL to a specific route and returns information about the route. This information, among other things, includes the controller that should be executed. Finally, the Symfony kernel executes the controller, which returns a response object.
All of the application routes are loaded from a single routing configuration file, usually app/config/routing.yml file, as shown by our test app:
app: resource: "@AppBundle/Controller/" type: annotation
The app is simply one of many possible entries. Its resource value points to AppBundle controller directory, and type is set to annotation which means that the class annotations will be read to specify exact routes.
We can define a route with several variations. One of them is shown in the following block:
// Basic Route Configuration
/**
* @Route("/")
*/
public function homeAction()
{
// ...
}
// Routing with Placeholders
/**
* @Route("/catalog/product/{sku}")
*/
public function showAction($sku)
{
// ...
}
// >>Required<< and Optional Placeholders
/**
* @Route("/catalog/product/{id}")
*/
public function indexAction($id)
{
// ...
}
// Required and >>Optional<< Placeholders
/**
* @Route("/catalog/product/{id}", defaults={"id" = 1})
*/
public function indexAction($id)
{
// ...
}The preceding examples show several ways we can define our route. The interesting one is the case with required and optional parameter. If we think about it, removing ID from the latest example will match the example before it with sku. The Symfony router will always choose the first matching route it finds. We can solve the problem by adding regular expression requirements attributed on @Route annotation as follows:
@Route(
"/catalog/product/{id}",
defaults={"id": 1},
requirements={"id": "\d+"}
)There is more to be said about controllers and routing, as we will see once we start building our application.