21.10.2015 Views

1-33

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Routing<br />

Symfony2 – Franz Jordán 2011<br />

Beautiful URLs are an absolute must for any serious web application. This means leaving behind<br />

ugly URLs like index.php?article_id=57 in favor of something like /read/intro-tosymfony.<br />

Having flexibility is even more important. What if you need to change the URL of a page<br />

from /blogto /news? How many links should you need to hunt down and update to make the<br />

change? If you're using Symfony's router, the change is simple.<br />

The Symfony2 router lets you define creative URLs that you map to different areas of your<br />

application. By the end of this chapter, you'll be able to:<br />

Create complex routes that map to controllers<br />

Generate URLs inside templates and controllers<br />

Load routing resources from bundles (or anywhere else)<br />

Debug your routes<br />

Routing in Action<br />

A route is a map from a URL pattern to a controller. For example, suppose you want to match<br />

any URL like /blog/my-post or /blog/all-about-symfony and send it to a controller that<br />

can look up and render that blog entry. The route is simple:<br />

# app/config/routing.yml<br />

blog_show:<br />

pattern: /blog/{slug}<br />

defaults: { _controller: AcmeBlogBundle:Blog:show }<br />

The pattern defined by the blog_show route acts like /blog/* where the wildcard is given the<br />

nameslug. For the URL /blog/my-blog-post, the slug variable gets a value of my-blogpost,<br />

which is available for you to use in your controller (keep reading).<br />

The _controller parameter is a special key that tells Symfony which controller should be<br />

executed when a URL matches this route. The _controller string is called the logical name. It<br />

follows a pattern that points to a specific PHP class and method:<br />

// src/Acme/BlogBundle/Controller/BlogController.php<br />

namespace Acme\BlogBundle\Controller;<br />

use Symfony\Bundle\FrameworkBundle\Controller\Controller;<br />

class BlogController extends Controller<br />

{<br />

public function showAction($slug)<br />

{<br />

$blog = // use the $slug varible to query the database<br />

}<br />

}<br />

return $this->render('AcmeBlogBundle:Blog:show.html.twig', array(<br />

));<br />

'blog' => $blog,<br />

55

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!