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.


    path:     /blog/{slug}
    defaults: { _controller: AcmeDemoBundle:Blog:show }
    methods:   [GET]
    path:     /blog/{slug}
    defaults: { _controller: AcmeDemoBundle:Blog:update }
    methods:   [PUT]
    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