Symfony2CookBook:如何在路由中使用GET和POST以外的HTTP方法

本文介绍了如何在路由中使用HTTP方法,包括GET、POST之外的方法,如PUT和DELETE,并讲解了如何在不支持这些方法的浏览器中通过_method参数进行模拟。

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来显示、修改和删除它。

1
2
3
4
5
6
7
8
9
10
11
12
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




本文转自 firehare 51CTO博客,原文链接:http://blog.51cto.com/firehare/1257690,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值