21.10.2015 Views

1-33

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Symfony2 – Franz Jordán 2011<br />

integer. Fortunately, regular expression requirements can easily be added for each parameter.<br />

For example:<br />

blog:<br />

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

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

requirements:<br />

page: \d+<br />

The \d+ requirement is a regular expression that says that the value of the {page} parameter<br />

must be a digit (i.e. a number). The blog route will still match on a URL like /blog/2 (because<br />

2 is a number), but it will no longer match a URL like /blog/my-blog-post (because myblog-post<br />

is not a number).<br />

As a result, a URL like /blog/my-blog-post will now properly match the blog_show route.<br />

URL route parameters<br />

/blog/2 blog {page} = 2<br />

/blog/my-blog-post blog_show {slug} = my-blog-post<br />

Earlier Routes always Win<br />

What this all means is that the order of the routes is very important. If theblog_show route<br />

were placed above the blog route, the URL /blog/2 would matchblog_show instead<br />

of blog since the {slug} parameter of blog_show has no requirements. By using proper<br />

ordering and clever requirements, you can accomplish just about anything.<br />

Since the parameter requirements are regular expressions, the complexity and flexibility of each<br />

requirement is entirely up to you. Suppose the homepage of your application is available in two<br />

different languages, based on the URL:<br />

homepage:<br />

pattern: /{culture}<br />

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

requirements:<br />

culture: en|fr<br />

For incoming requests, the {culture} portion of the URL is matched against the regular<br />

expression(en|fr).<br />

/ {culture} = en<br />

/en {culture} = en<br />

/fr<br />

{culture} = fr<br />

/es won't match this route<br />

60

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

Saved successfully!

Ooh no, something went wrong!