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.

Symfony2 – Franz Jordán 2011<br />

Even though all routes are loaded from a single file, it's common practice to include additional<br />

routing resources from inside the file. See the Including External Routing Resources section for<br />

more information.<br />

Basic Route Configuration<br />

Defining a route is easy, and a typical application will have lots of routes. A basic route consists<br />

of just two parts: the pattern to match and a defaults array:<br />

_welcome:<br />

pattern: /<br />

defaults: { _controller: AcmeDemoBundle:Main:homepage }<br />

This route matches the homepage (/) and maps it to<br />

the AcmeDemoBundle:Main:homepage controller. The _controller string is translated by<br />

Symfony2 into an actual PHP function and executed. That process will be explained shortly in<br />

the Controller Naming Pattern section.<br />

Routing with Placeholders<br />

Of course the routing system supports much more interesting routes. Many routes will contain<br />

one or more named "wildcard" placeholders:<br />

blog_show:<br />

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

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

The pattern will match anything that looks like /blog/*. Even better, the value matching<br />

the {slug}placeholder will be available inside your controller. In other words, if the URL<br />

is /blog/hello-world, a $slug variable, with a value of hello-world, will be available in<br />

the controller. This can be used, for example, to load the blog post matching that string.<br />

The pattern will not, however, match simply /blog. That's because, by default, all placeholders<br />

are required. This can be changed by adding a placeholder value to the defaults array.<br />

Required and Optional Placeholders<br />

To make things more exciting, add a new route that displays a list of all the available blog posts<br />

for this imaginary blog application:<br />

blog_show:<br />

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

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

So far, this route is as simple as possible - it contains no placeholders and will only match the<br />

exact URL /blog. But what if you need this route to support pagination,<br />

where /blog/2 displays the second page of blog entries? Update the route to have a<br />

new {page} placeholder:<br />

blog:<br />

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

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

58

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

Saved successfully!

Ooh no, something went wrong!