FOSRestBundle功能包:自动路由生成-单REST风格控制器
原文出處: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: jsonMany 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\UsersControllerThis 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代表集合。因此下面示例將正常工作:
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 :
特別注意 link 和 unlink: 本功能包并未實現請求監聽器可以如實體一樣提取資源。一個好的實現可以在這里找到:
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).
它也包含了一些如何使用它的例子。 link 和 unlink已經過時了(在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}),那么您將不得不添加一些配置:
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风格控制器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 欠费停机会影响征信吗 手机欠费上不上征信
- 下一篇: wat是什么文件