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:     rest
    resource: 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] /users
    public function getUsersAction()
    {} // "get_users"     [GET] /users
    public function newUsersAction()
    {} // "new_users"     [GET] /users/new
    public function postUsersAction()
    {} // "post_users"    [POST] /users
    public function patchUsersAction()
    {} // "patch_users"   [PATCH] /users
    public function getUserAction($slug)
    {} // "get_user"      [GET] /users/{slug}
    public function editUserAction($slug)
    {} // "edit_user"     [GET] /users/{slug}/edit
    public 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}/lock
    public function banUserAction($slug)
    {} // "ban_user"      [PATCH] /users/{slug}/ban
    public function removeUserAction($slug)
    {} // "remove_user"   [GET] /users/{slug}/remove
    public function deleteUserAction($slug)
    {} // "delete_user"   [DELETE] /users/{slug}
    public function getUserCommentsAction($slug)
    {} // "get_user_comments"    [GET] /users/{slug}/comments
    public function newUserCommentsAction($slug)
    {} // "new_user_comments"    [GET] /users/{slug}/comments/new
    public function postUserCommentsAction($slug)
    {} // "post_user_comments"   [POST] /users/{slug}/comments
    public 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}/edit
    public 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}/vote
    public function removeUserCommentAction($slug, $id)
    {} // "remove_user_comment"  [GET] /users/{slug}/comments/{id}/remove
    public 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中忽略资源名方法名将出现重复,因此需要调用特定的方法:getActioncgetAction,其中c代表集合。因此下面示例将正常工作:


<?php
use FOS\RestBundle\Routing\Cla***esourceInterface;
class UserController implements Cla***esourceInterface
{
    ..
    public function cgetAction()
    {} // "get_users"     [GET] /users
    public function newAction()
    {} // "new_users"     [GET] /users/new
    public 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] /users
    public function newAction()
    {} // "new_users"     [GET] /users/new
    public 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风格控制器