设计路由器和RESTful 架构中的控制器
RESTful 架构中控制器的简单示例表明每个控制器有四个操作 - index
、create
、update
、delete
-- 对应GET、POST、PUT、DELETE。但除此之外,我仍然发现了十几个小决定:
- 您对资源集合(
example.com/things
)的控制器与对单个资源(example.com/things)的控制器是否不同? /123
)? - 对于单独的资源,是否最好将 id 作为参数传递给操作,或者将其设置为控制器类中的成员变量?
- 你如何进行 URI 路由?旧的经过验证的
example.com/{controller}/{action}
方法有点崩溃了。 - 那么
example.com/user/123/things
这样的从属资源呢?您是否必须明确定义这些路线的每条路线,或者是否有办法编写良好的通用规则? - 您是否区分 API 请求和浏览器请求,或者是否通过相同的控制器和/或控制器方法引导它们?
显然,你可以用十几种不同的方式来解决这些问题,但如果其他人已经解决了这个问题,我真的不想重新发明轮子。我正在寻找任何建议,或者更好的一些好的教程来处理设计 RESTful mvc 框架时的这些(和其他相关)实际问题。
Simple examples of controllers in a RESTful architecture suggest four actions per controller -- index
, create
, update
, delete
-- corresponding with the GET, POST, PUT, and DELETE. But beyond that I still find a dozen little decisions:
- Do you have a different controller for resource collections (
example.com/things
) than you do for an individual resource (example.com/things/123
)? - With individual resources, is it preferable to pass the id in as a parameter to the action, or set it as a member variable in the controller class?
- How do you go about URI routing? The old tried-and-true
example.com/{controller}/{action}
approach kind of falls apart. - What about subordinate resources like
example.com/user/123/things
? Do you have to explicitly define every route for these or is there a way to write a good general rule? - Do you differentiate between API requests and browser requests, or do you channel them through the same controller and/or controller methods?
Obviously, you could go about these things a dozen different ways, but I'd really like to not have to re-invent the wheel if others have hashed through the problem. I'm looking for any advice or maybe better some good tutorials that deal with these (and other related) practical issues in designing a RESTful mvc framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的控制器有 Get()、Put()、Post()、Delete() 等方法。我认为使用“操作术语”会混淆问题。
我总是为集合和单个事物创建不同的控制器。对我来说,它们是非常不同的资源,我希望 HTTP 方法做不同的事情。
路由我的做法与大多数框架不同。我不会匹配整个网址,而是逐段匹配。它类似于 子资源 在 JAX-RS 中工作
对于只有少量不同资源的服务,那么使用正则表达式样式的 url 模式匹配就可以了。我发现一旦你开始处理数百个资源,它就开始崩溃。
My controllers have methods Get(), Put(), Post(), Delete(), etc. I think using the "action terms" confuses the issue.
I always create a different controller for collections and single things. To me they are very different resources and I want the HTTP methods to do different things.
Routing I do differently than most frameworks. I don't match on the entire url, but on a segment by segment basis. It is similar to the way SubResources work in JAX-RS
For services that only have a small number of distinct resources then using regex style url pattern matching is fine. I just found it started to break down once you start dealing with hundreds of resources.