• 原文出处:5-automatic-route-generation_single-restful-controller.md

  • 原文作者:FriendsOfSymfony

  • 授权许可:创作共用协议

  • 翻译人员:FireHare

  • 校对人员:

  • 适用版本:FOSRestBundle 0.12.0

  • 文章状态:草译阶段

Routing

The RestBundle provides custom route loaders to help in defining REST friendly routes as well as reducing the manual work of configuring routes and the given requirements (like making sure that only GET may be used in certain routes etc.).

RestBundle功能包提供自定义路由加载器,帮助在定义REST友好路由时减少手工配置路由和指定要求的工作(就如在某些路由中确定仅使用GET等)。

You may specify a default_format that the routing loader will use for the _format parameter if none is specified.

您可以指定一个 default_format,如果 _format 参数被指定为none的话,路由加载器将使用该参数。

# app/config/config.yml
fos_rest:routing_loader:default_format: json

Many of the features explained below are used in the following example code:

许多特性将在下面的示例代码中说明:

https://github.com/liip/LiipHelloBundle/blob/master/Controller/RestController.php

Single RESTful controller routes

In this section we are looking at controllers for resources without sub-resources.Handling of sub-resources requires some additional considerations which are explained in the next section.

在本节,我们谈论的是没有子资源的资源,关于子资源的处理需要额外的考虑,我们将在下一节中进行说明。

# app/config/routing.yml
users:type:     restresource: Acme\HelloBundle\Controller\UsersController

This will tell Symfony2 to automatically generate proper REST routes from your UsersController action names.Notice type: rest option. It's required so that the RestBundle can find which routes are supported.

上述配置将告诉Symfony2自动从您的UsersController的Action名中自动生成REST风格的路由。请注意 type: rest 选项,它被要求以便让RestBundle功能包发现哪个路由被支持。

Notice the name_prefix: my_bundle_ option. It's useful to prefix the generated controller routes to organize your several resources paths. Take care that you can use name_prefix on an import only when the file is imported itself with the type:rest. The parent option is used in sub-resources as we will see in the next section for multiple RESTful controller routes.

注意name_prefix: my_bundle_ 选项,它是非常有用的,可以生成控制器路由前缀,用来组织您多个资源的路径。要小心,您只可以在文件使用 type:rest 导入时使用name_prefix。 parent 选项被用于子资源,因此我们将在下一节的多REST风格控制器路由中看到。

Define resource actions

<?php
class UsersController
{public function optionsUsersAction(){} // "options_users" [OPTIONS] /userspublic function getUsersAction(){} // "get_users"     [GET] /userspublic function newUsersAction(){} // "new_users"     [GET] /users/newpublic function postUsersAction(){} // "post_users"    [POST] /userspublic function patchUsersAction(){} // "patch_users"   [PATCH] /userspublic function getUserAction($slug){} // "get_user"      [GET] /users/{slug}public function editUserAction($slug){} // "edit_user"     [GET] /users/{slug}/editpublic function putUserAction($slug){} // "put_user"      [PUT] /users/{slug}public function patchUserAction($slug){} // "patch_user"    [PATCH] /users/{slug}public function lockUserAction($slug){} // "lock_user"     [PATCH] /users/{slug}/lockpublic function banUserAction($slug){} // "ban_user"      [PATCH] /users/{slug}/banpublic function removeUserAction($slug){} // "remove_user"   [GET] /users/{slug}/removepublic function deleteUserAction($slug){} // "delete_user"   [DELETE] /users/{slug}public function getUserCommentsAction($slug){} // "get_user_comments"    [GET] /users/{slug}/commentspublic function newUserCommentsAction($slug){} // "new_user_comments"    [GET] /users/{slug}/comments/newpublic function postUserCommentsAction($slug){} // "post_user_comments"   [POST] /users/{slug}/commentspublic function getUserCommentAction($slug, $id){} // "get_user_comment"     [GET] /users/{slug}/comments/{id}public function editUserCommentAction($slug, $id){} // "edit_user_comment"    [GET] /users/{slug}/comments/{id}/editpublic function putUserCommentAction($slug, $id){} // "put_user_comment"     [PUT] /users/{slug}/comments/{id}public function postUserCommentVoteAction($slug, $id){} // "post_user_comment_vote" [POST] /users/{slug}/comments/{id}/votepublic function removeUserCommentAction($slug, $id){} // "remove_user_comment"  [GET] /users/{slug}/comments/{id}/removepublic function deleteUserCommentAction($slug, $id){} // "delete_user_comment"  [DELETE] /users/{slug}/comments/{id}public function linkUserAction($slug){} // "link_user_friend"     [LINK] /users/{slug}public function unlinkUserAction($slug){} // "link_user_friend"     [UNLINK] /users/{slug}
}

That's all. All your resource (UsersController) actions will get mapped to the proper routes as shown in the comments in the above example. Here are a few things to note:

综上所述,在上面的示例中您全部资源(UsersController)的Action将象注释中显示的那样映射到适当的路由。这里几点要注意:

Implicit resource name definition(隐性资源名定义)

Its possible to omit the User part of the method names when the Controller implements the Cla***esourceInterface. In this case FOSRestBundle can determine the resource based on the Controller name. However for this to work its important to use singular names in the Controller.However by omitting the resource name from the methods getUserAction and getUsersAction there would be an overlap of method names there is a special convention to call the methods getAction and cgetAction, where the c standard for collection. So the following would work as well.

当控制器实现了Cla***esourceInterface接口时,可以忽略User方法名的一部分。在本例中 FOSRestBundle 可以确定基于控制器名的资源。然而要使它正常工作的重点在于在控制器中使用特殊的方法名。然而从 getUserActiont 和 getUsersAction中忽略资源名方法名将出现重复,因此需要调用特定的方法:getAction 和 cgetAction,其中c代表集合。因此下面示例将正常工作:

<?php
use FOS\RestBundle\Routing\Cla***esourceInterface;
class UserController implements Cla***esourceInterface
{..public function cgetAction(){} // "get_users"     [GET] /userspublic function newAction(){} // "new_users"     [GET] /users/newpublic function getAction($slug){} // "get_user"      [GET] /users/{slug}..public function getCommentsAction($slug){} // "get_user_comments"    [GET] /users/{slug}/comments..
}

Finally its possible to override the resource name derived from the Controller name via the @RouteResource annotation:

最终将通过@RouteResource注释覆盖从控制器名推导的资源名:

<?php
use FOS\RestBundle\Controller\Annotations\RouteResource;
/*** @RouteResource("User")*/
class FooController
{..public function cgetAction(){} // "get_users"     [GET] /userspublic function newAction(){} // "new_users"     [GET] /users/newpublic function getAction($slug){} // "get_user"      [GET] /users/{slug}..public function getCommentsAction($slug){} // "get_user_comments"    [GET] /users/{slug}/comments..
}

REST Actions

There are 5 actions that have special meaning in regards to REST and have the following behavior:

这里有5种Action对于REST有着特殊的意思,并有以下行为:

  • get - this action accepts GET requests to the url /resources and returns all resources for this type. Shown asUsersController::getUsersAction() above. This action also accepts GET requests to the url /resources/{id} andreturns a single resource for this type. Shown as UsersController::getUserAction() above.

  • get - 该Action接受到 url/resources 的 GET 请求,并返回该类型的全部资源。如上例UsersController::getUsersAction() 所示。该Action也接受到 /url/resources/{id} 的 GET 请求,并为该类型返回单个资源。如上例 UsersController::getUserAction() 所示。

  • post - this action accepts POST requests to the url /resources and creates a new resource of this type. Shownas UsersController::postUsersAction() above.

  • post - 该Action 接受到 url/resources 的 POST 请求,并创建一个该类型的新资源。如上例 UsersController::postUsersAction() 所示。

  • put - this action accepts PUT requests to the url /resources/{id} and updates a single resource for this type.Shown as UsersController::putUserAction() above.

  • put - 该 Action 接受到 url/resources/{id} 的PUT 请求,并更新该类型的单个资源。如上例 UsersController::putUserAction() 所示。

  • delete - this action accepts DELETE requests to the url /resources/{id} and deletes a single resource for thistype. Shown as UsersController::deleteUserAction() above.

  • delete - 该 Action 接受到 url /resources/{id} 的 DELETE 请求,并删除该类型的单个资源。如上例 UsersController::deleteUserAction() 所示。

  • patch - this action accepts PATCH requests to the url /resources and is supposed to partially modify collectionof resources (e.g. apply batch modifications to subset of resources). Shown as UsersController::patchUsersAction() above.This action also accepts PATCH requests to the url /resources/{id} and is supposed to partially modify the resource.Shown as UsersController::patchUserAction() above.

  • patch - 该Action 接受到  url /resources 的 PATCH 请求,并且应该是部分修定资源集(如应用在批量修改资源子集),如上例UsersController::patchUsersAction() 所示。该Action还接受到 url /resources/{id} 的PATCH 请求。如上例UsersController::patchUserAction() 所示。

  • option - this action accepts OPTION requests to the url /resources and is supposed to return a list of RESTresources that the user has access to.  Shown as UsersController::userAction() above.

  • option - 该Action接受到 url /resources 的 OPTION 请求,并且应该是返回一个REST风格的供用户访问的资源列表,如上例 UsersController::userAction() 所示。

  • link - this action accepts LINK requests to the url /resources/{id} and is supposed to return nothing but astatus code indicating that the specified resources were linked. It is used to declare a resource as related to an other one.When calling a LINK url you must provide in your header at least one link header formatted as follow :<http://example.com/resources/{id}\>; rel="kind_of_relation"

  • link - 该Action接受到 url/resources/{id} 的 LINK 请求,并且应该除了一个表示特定资源链接的状态码外,没有任何返回。它常用来声明资源与另一资源相关。当调用LINK url时,您必须在您的头信息提供至少一个如下格式链接头:

    <http://example.com/resources/{id}\>; rel="kind_of_relation"

  • unlink - this action accepts UNLINK requests to the url /resources/{id} and is supposed to return nothing buta status code indicating that the specified resources were unlinked. It is used to declare that some resources are notrelated anymore. When calling a UNLINK url you must provide in your header at least one link header formatted as follow :<http://example.com/resources/{id}\>; rel="kind_of_relation"

  • unlink - 该Action接受到 url/resources/{id} 的 UNLINK 请求,并且应该除了一个表示断开特定资源链接的状态码外,没有任何返回。 当调用UNLINK url时,您必须在您的头信息提供至少一个如下格式链接头:

    <http://example.com/resources/{id}\>; rel="kind_of_relation"

Important note about link and unlink: The implementation of the request listener extracting the resources as entities is not provided by this bundle. A good implementation can be found here :

特别注意 linkunlink: 本功能包并未实现请求监听器可以如实体一样提取资源。一个好的实现可以在这里找到:

http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

It also contains some examples on how to use it. link and unlink were obsoleted by RFC 2616, RFC 5988 aims to define it in a more clear way. Using these methods is not risky, but remains unclear (cf. issues 323 and 325).

它也包含了一些如何使用它的例子。 linkunlink已经过时了(在RFC 2616、RFC5988中),目的是为了更清晰地定义。使用这些方法没有风险,但仍然不够清晰。(参见问题323和325)。

Conventional Actions(常规Action)

HATEOAS, or Hypermedia as the Engine of Application State, is an aspect of REST which allows clients to interact with the REST service with hypertext - most commonly through an HTML page. There are 3 Conventional Action routings that are supported by this bundle:

HATEOAS,或超媒体作为应用程序状态引擎,是REST的一个方面,它允许用户与有着超文本的REST服务交互,最常见的是通过HTML页。这里有3种常规Action路由被本功能包支持:

  • new - A hypermedia representation that acts as the engine to POST. Typically this is a form that allows the clientto POST a new resource. Shown as UsersController::newUsersAction() above.

  • new - 一个超媒体表示,作为引擎去POST。通常情况下是一个允许用户POST新资源的表单。如上例 UsersController::newUsersAction() 所示。

  • edit - A hypermedia representation that acts as the engine to PUT. Typically this is a form that allows the clientto PUT, or update, an existing resource. Shown as UsersController::editUserAction() above.

  • edit - 一个超媒体表示,作为引擎去PUT。通常情况下是一个允许用户去PUT或更新一个已存在资源的表单,如上例 UsersController::editUserAction() 所示。

  • remove - A hypermedia representation that acts as the engine to DELETE. Typically this is a form that allows theclient to DELETE an existing resource. Commonly a confirmation form. Shown as UsersController::removeUserAction() above.

  • remove - 一个超媒体表示,作为引擎去 DELETE。通常情况下是一个允许用户去 DELETE 一个已存在的资源。通常还是个确认表单。如上例UsersController::removeUserAction() 所示。

Custom PATCH Actions(自定义PATCH Action)

All actions that do not match the ones listed in the sections above will register as a PATCH action. In the controller shown above, these actions are UsersController::lockUserAction(), UsersController::banUserAction() andUsersController::voteUserCommentAction(). You could just as easily create a method called UsersController::promoteUserAction() which would take a PATCH request to the url /users/{slug}/promote.This allows for easy updating of aspects of a resource, without having to deal with the resource as a whole at the standard PATCH or PUT endpoint.

所有没有本节以前列出的Action都被注册为 PATCH Action。如上例控制器中的UsersController::lockUserAction()、UsersController::banUserAction()UsersController::voteUserCommentAction()。您可以很容易地创建一个名为UsersController::promoteUserAction()的方法,它将发送PATCH请求到 url/users/{slug}/promote。这就允许很容易地更新资源的某些方面,而无需将资源被为一个整体,标准的PATCH或PUT端点来进行处理。

Sub-Resource Actions(子资源Action)

Of course it's possible and common to have sub or child resources. They are easily defined within the same controller by following the naming convention ResourceController::actionResourceSubResource() - as seen in the example above with UsersController::getUserCommentsAction(). This is a good strategy to follow when the child resource needs the parent resource's ID in order to look up itself.

当然,拥有子资源是可能的也是常见的。遵循命名约定 ResourceController::actionResourceSubResource(),可以很方便地在同一控制器中定义它们,如上例UsersController::getUserCommentsAction()所示。这遵循了一个很好的策略,子资源需要父资源ID,以便查找自已。

Optional {_format} in route(路由中的可选项 {_format})

By default, routes are generated with {_format} string. If you want to get clean urls (/orders instead /orders.{_format}) then all you have to do is add some configuration:

缺省状态下,路由是带有 {_format} 字符串的。如果您想得到简洁的urls(用/orders来代替/orders.{_format}),那么您将不得不添加一些配置:

# app/config/config.yml
fos_rest:routing_loader:include_format:       false

The {_format} route requirement is automatically positionned using the available listeners. So by default, the  requirement will be {json|xml|html}. If you want to limit or add a custom format, you can do so by overriding it with the @Route annotation(or another one extending it, like @Get, @Post...):

{_format} 路由请求是由可用的监听器自动定位的。因此在缺省状态下,请求将是 {json|xml|html}。如果您想限制或添加自定义格式,您可以通过用@Route注释覆写它(或通过另一个来扩展它,如@Get、@Post...)即可。

<?php
use FOS\RestBundle\Controller\Annotations\Route;../*** @Route(requirements={"_format"="json|xml"})*/public function getAction($slug){}..
}

That was it!

Return to the index or continue reading about Automatic route generation: multiple RESTful controllers.

返回指南页或继续阅读自动路由生成:多REST风格控制器

FOSRestBundle功能包:自动路由生成-单REST风格控制器相关推荐

  1. FOSRestBundle功能包:视图层

    原文出处:2-the-view-layer.md 原文作者:FriendsOfSymfony 授权许可:创作共用协议 翻译人员:FireHare 校对人员: 适用版本:FOSRestBundle 0. ...

  2. FOSRestBundle功能包:概述

    原文出处:README.md 原文作者:FriendsOfSymfony 授权许可:创作共用协议 翻译人员:FireHare 校对人员: 适用版本:FOSRestBundle 0.12.0 文章状态: ...

  3. python表情包多样化图形化聊天室_Python还有这功能:自动生成表情包,从此斗图无敌手!...

    原标题:Python还有这功能:自动生成表情包,从此斗图无敌手!

  4. 告别加班/解放双手提高单测覆盖率之Java 自动生成单测代码神器推荐

    一.背景 很多公司对分支单测覆盖率会有一定的要求,比如 单测覆盖率要达到 60% 或者 80%才可以发布. 有时候工期相对紧张,就优先开发功能,测试功能,然后再去补单元测试. 但是编写单元测试又比较浪 ...

  5. web项目中填写sql信息自动动态生成报表功能(springboot)

    (一)大概 背景: 需求就是设计一个自定义报表功能,当需要新报表时,能够快速的构建. 经过初步的构思,有至少三种方式可以实现: 构建demo代码,一个报表对应编写一套代码,不过可以将重复代码提取,尽可 ...

  6. R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义函数在三线表中添加p值

    R语言使用table1包绘制(生成)三线表.使用单变量分列构建三线表.编写自定义函数在三线表中添加p值 目录

  7. R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、设置transpose参数转置三线表、变量作为列,子组(strata)作为行

    R语言使用table1包绘制(生成)三线表.使用单变量分列构建三线表.设置transpose参数转置三线表.变量作为列,子组(strata)作为行 目录

  8. R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、自定义overall的标签名称

    R语言使用table1包绘制(生成)三线表.使用单变量分列构建三线表.自定义overall的标签名称 目录

  9. R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、为指定变量添加单位信息、自定义overall的标签名称

    R语言使用table1包绘制(生成)三线表.使用单变量分列构建三线表.为指定变量添加单位信息.自定义overall的标签名称 目录

最新文章

  1. Linux下测试的c++的使用
  2. VTK序列图像的读取
  3. S/4HANA for Customer Management里的搜索分页处理
  4. 6、struts.properties配置详解
  5. android数据库给单选赋值,如何使用android studio将单选按钮的值保存到mysql数据库?...
  6. nsdictionary获取值_获得nsdictionary值
  7. C++类中静态变量和静态方法使用介绍!
  8. php sqlite创建表,php – 使用SQLite创建列表树
  9. MacOS六个常用的终端命令
  10. Jquery ajax, Axios, Fetch区别之我见
  11. Shell编程之变量的高级用法
  12. ML之LIME:基于boston波士顿房价数据集回归预测利用LIME/SP-LIME局部解释图/权重图结合RF随机森林模型实现模型事后解释案例之详细攻略
  13. keil5——安装教程附资源包
  14. 基于双碳背景和趋势讲述AcrelEMS企业微电网能效管理系统-Susie 周
  15. 蓝桥杯 Java 自行车停放(双向链表解法)
  16. spring注解开发配置spring父子容器
  17. 数据库系统原理(1)--绪论
  18. ps cc 生成html,ps cc中怎么生成图像资源?
  19. python数字1 3怎么表示_Python3生成手写体数字方法
  20. 自学运维真的学不下去了,有靠谱的培训班吗?

热门文章

  1. shell脚本学习(一):shell脚本开发的基本规范和习惯
  2. PHP5各个版本的新功能和新特性总结(转载 http://www.jb51.net/article/48150.htm)
  3. “没有找到iliertutil.dll,因此这个应用程序未能启动。”文件拷贝 PE 或者 dos...
  4. php文件上传错误代码
  5. c++ 重载 重写_关于C/C++中的++i和i++实现机制的探讨
  6. beatsx白灯闪三下开不了机_beats X耳机不开机维修,beatsx耳机闪白灯是什么问题...
  7. java 高并发第三阶段实战_Java 高并发第三阶段实战---Java并发包深入解析与使用详解...
  8. java线程runnable_Java 线程状态之 RUNNABLE
  9. Android开发之PCM录音实时播放的实现方法 | 边录音边播放 |PCM录音播放无延迟 | 录音无杂音 | 录音无噪音
  10. java 基本语法与流程控制_Java基础语法之控制流程