// src/Acme/BlogBundle/Controller/BlogController.php namespace Acme\BlogBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class BlogController extends Controller { public function showAction($slug) { $blog = // use the $slug variable to query the database return $this->render('AcmeBlogBundle:Blog:show.html.twig', array( 'blog' => $blog, )); } }
Congratulations! You've just created your first route and connected it to a controller. Now, when you visit /blog/my-post, the showAction controller will be executed and the $slug variable will be equal to my-post. This is the goal of the Symfony2 router: to map the URL of a request to a controller. Along the way, you'll learn all sorts of tricks that make mapping even the most complex URLs easy.
Routing: Under the Hood When a request is made to your application, it contains an address to the exact "resource" that the client is requesting. This address is called the URL, (or URI), and could be /contact, /blog/read-me, or anything else. Take the following HTTP request for example: GET /blog/my-blog-post
Listing 6-3
The goal of the Symfony2 routing system is to parse this URL and determine which controller should be executed. The whole process looks like this: 1. The request is handled by the Symfony2 front controller (e.g. app.php); 2. The Symfony2 core (i.e. Kernel) asks the router to inspect the request; 3. The router matches the incoming URL to a specific route and returns information about the route, including the controller that should be executed; 4. The Symfony2 Kernel executes the controller, which ultimately returns a Response object.
The routing layer is a tool that translates the incoming URL into a specific controller to execute.
PDF brought to you by generated on June 20, 2012
Chapter 6: Routing | 55