How to use HTTP Methods beyond GET and POST in Routes

The HTTP method of a request is one of the requirements that can be checked when seeing if it matches a route. This is introduced in the routing chapter of the book "Routing" with examples using GET and POST. You can also use other HTTP verbs in this way. For example, if you have a blog post entry then you could use the same URL path to show it, make changes to it and delete it by matching on GET, PUT and DELETE.

在查看是否匹配路由时,请求中的HTTP方法将作为请求的一部分而被检查。这在"Routing"书中的路由章节通过使用GET和POST举例介绍过。您通过这样方式来使用其它HTTP动词。例如,如果您有一个博客文章条目,然后您就可以使用相同的URL路径,通过匹配GET、PUT和DELETE来显示、修改和删除它。

blog_show:
    path:     /blog/{slug}
    defaults: { _controller: AcmeDemoBundle:Blog:show }
    methods:   [GET]
blog_update:
    path:     /blog/{slug}
    defaults: { _controller: AcmeDemoBundle:Blog:update }
    methods:   [PUT]
blog_delete:
    path:     /blog/{slug}
    defaults: { _controller: AcmeDemoBundle:Blog:delete }
    methods:   [DELETE]

Faking the Method with _method(通过_method伪造方法)

The _method functionality shown here is disabled by default in Symfony 2.2 and enabled by default in Symfony 2.3. To control it in Symfony 2.2, you must call Request::enableHttpMethodParameterOverridebefore you handle the request (e.g. in your front controller). In Symfony2.3, use the http_method_override option.

_method 在这里显示的功能在Symfony 2.2中默认是禁用的,而在Symfony 2.3中默认是启用的。在Symfony 2.2中要控制它,您必须在您处理请求之前(如在您的前端控制器中)调用Request::enableHttpMethodParameterOverride。在Symfony 2.3中,则使http_method_override 配置项。


Unfortunately, life isn't quite this simple, since most browsers do notsupport sending PUT and DELETE requests. Fortunately Symfony2 provides youwith a simple way of working around this limitation. By including a _method parameter in the query string or parameters of an HTTP request, Symfony2 willuse this as the method when matching routes. Forms automatically include a hidden field for this parameter if their submission method is not GET or POST.See the related chapter in the forms documentationfor more information.

不幸的是,生活并非如此简单,因为大多数浏览器并不支持发送 PUT 和 DELETE 请求。幸运的是Symfony2 为您提供了一个简单方法来绕过这一限制。通过在HTTP请求中的查询字符串或参数中包含 _method 参数,Symfony2将在匹配路由时将其作为方法使用。如果表单提交方法不是GET或POST时,它们将自动为这一参数创建一个隐藏字段。更多情况请参见: the related chapter in the forms documentation