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 />

Adding HTTP Method Requirements<br />

In addition to the URL, you can also match on the method of the incoming request (i.e. GET,<br />

HEAD, POST, PUT, DELETE). Suppose you have a contact form with two controllers - one for<br />

displaying the form (on a GET request) and one for processing the form when it's submitted (on<br />

a POST request). This can be accomplished with the following route configuration:<br />

contact:<br />

pattern: /contact<br />

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

requirements:<br />

_method: GET<br />

contact_process:<br />

pattern: /contact<br />

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

requirements:<br />

_method: POST<br />

Despite the fact that these two routes have identical patterns (/contact), the first route will<br />

match only GET requests and the second route will match only POST requests. This means that<br />

you can display the form and submit the form via the same URL, while using distinct controllers<br />

for the two actions.<br />

If no _method requirement is specified, the route will match on all methods.<br />

Like the other requirements, the _method requirement is parsed as a regular expression. To<br />

matchGET or POST requests, you can use GET|POST.<br />

Advanced Routing Example<br />

At this point, you have everything you need to create a powerful routing structure in Symfony.<br />

The following is an example of just how flexible the routing system can be:<br />

article_show:<br />

pattern: /articles/{culture}/{year}/{title}.{_format}<br />

defaults: { _controller: AcmeDemoBundle:Article:show, _format: html }<br />

requirements:<br />

culture: en|fr<br />

_format: html|rss<br />

year: \d+<br />

As you've seen, this route will only match if the {culture} portion of the URL is<br />

either en or fr and if the {year} is a number. This route also shows how you can use a period<br />

between placeholders instead of a slash. URLs matching this route might look like:<br />

/articles/en/2010/my-post<br />

/articles/fr/2010/my-post.rss<br />

The Special _format Routing Parameter<br />

This example also highlights the special _format routing parameter. When using this<br />

parameter, the matched value becomes the "request format" of the Requestobject. Ultimately,<br />

the request format is used for such things such as setting theContent-Type of the response<br />

(e.g. a json request format translates into aContent-Type of application/json). It can<br />

61

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

Saved successfully!

Ooh no, something went wrong!