brightmarch/restful-bundle

一个用于轻松创建RESTful资源的实用工具包。

dev-master 2014-06-10 14:49 UTC

This package is not auto-updated.

Last update: 2024-09-14 12:45:00 UTC


README

这是一个非常小巧但功能强大的Symfony2工具包,用于快速构建RESTful资源(特别是HTTP API)。

安装

安装相对简单。它需要三个步骤。首先,将正确的依赖项添加到您的composer.json文件中,并安装新的工具包。

"brightmarch/restful-bundle": "1.0.0"

您可以安全地假设master分支总是是最新的。

$ composer.phar install brightmarch/restful-bundle

安装完成后,将其添加到主app/AppKernel.php文件中的$bundles数组中。您不希望它只作为开发系统的一部分。

$bundles = array(
    new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
    // ... other bundles ... //
    new Brightmarch\Bundle\RestfulBundle\BrightmarchRestfulBundle(),
);

安装完成,您现在可以开始构建RESTful资源了。

用法

首先,您可能想从自己的工具包开始。您希望使用此工具包的每个资源都必须扩展Brightmarch\Bundle\RestfulBundle\Controller\RestfulController控制器。

示例控制器

<?php

namespace Sample\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Brightmarch\Bundle\RestfulBundle\Controller\RestfulController;
use Brightmarch\Bundle\RestfulBundle\Exceptions\HttpUnauthorizedException;

class AccountsController extends RestfulController
{

    public function indexAction()
    {
        // Describe what content types this resource supports.
        $this->resourceSupports('application/json', 'application/xml', 'text/html');

        $accounts = $this->get('doctrine')
            ->getManager()
            ->getRepository('SampleAppBundle:Account')
            ->findAll();

        // The type of the view will automatically
        // be found based on the Accept header.
        $parameters = [
            'accounts' => $accounts
        ];

        return $this->renderResource('SampleAppBundle:Accounts:accounts', $parameters);
    }

}

您必须描述此资源支持的内容类型。这意味着如果客户端发送一个此资源不接受的内容类型的Accept头,将返回一个406 Unacceptable响应。因为此资源支持三种内容类型,所以您必须有三个不同的视图:accounts.json.twig、accounts.xml.twig和accounts.html.twig。

index.json.twig

{% autoescape false %}
[
    {% for account in accounts %}
        {
            "id": {{ account.getId|json_encode }},
            "name": {{ account.getName|json_encode }}
        }
    {% endfor %}
]
{% endautoescape %}

index.xml.twig

<?xml version="1.0" encoding="UTF-8"?>
<accounts>
    {% for account in accounts %}
        <account>
            <id>{{ account.getId }}</id>
            <name>{{ account.getName }}</name>
        </account>
    {% endfor %}
</accounts>

index.html.twig

<!doctype html>
<html>
<head>
    <title>Accounts Resource</title>
</head>
<body>
    <ul>
        {% for account in accounts %}
            <li>{{ account.getName }}</li>
        {% endfor %}
    </ul>
</body>
</html>

一个稍微复杂一点的控制器可能会找到一个实体并将其渲染出来。您希望以请求的格式渲染它。您只需为这些格式创建模板即可。别忘了,如果需要,资源应相互链接。以下是一个Account的示例模板。

{% autoescape false %}
{
    "id": {{ account.getId }},
    "created_at": {{ account.getCreatedAt|format_date|json_encode }},
    "updated_at": {{ account.getUpdatedAt|format_date|json_encode }},
    "name": {{ account.getName|json_encode }},
    "identifier": {{ account.getIdentifier|json_encode }},
    "email": {{ account.getEmail|json_encode }},
    "lang": {{ account.getLang|json_encode }},
    "_links": [
        {
            "rel": "self",
            "url": {{ url('sample_app_view_account', { 'id': account.getId })|json_encode }}
        },
        {
            "rel": "alt",
            "url": {{ url('sample_app_view_account_identifier', { 'identifier': account.getIdentifier })|json_encode }}
        }
    ]
}
{% endautoescape %}

您会注意到有两个_links记录。一个直接指向它自己,另一个提供到同一资源的替代URL。

错误

此工具包支持正确处理HTTP错误。它包含几个用于处理错误的异常。它们包括

  • 400: HttpBadSyntaxException
  • 405: HttpMethodNotAllowedException
  • 406: HttpNotAcceptableException
  • 409: HttpConflictException
  • 415: HttpUnsupportedMediaTypeException
  • 510: HttpNotExtendedException
  • 404: HttpNotFoundException
  • 401: HttpUnauthorizedException

您负责渲染您的错误。有一个默认模板位于Resources/views/Restful/error.json.twig。您应该熟悉在Symfony中使用事件监听器捕获内核异常,以自动将所有错误作为RESTful响应返回。错误响应模板如下所示

{% autoescape false %}
{
    "httpCode": {{ httpCode }},
    "message": {{ message|json_encode }}
}
{% endautoescape %}

HTTP代码也将作为响应有效负载的一部分发送回。例如,向上述资源发出此请求将导致406错误

$ curl -v -H "Accept: invalid/type" http://example.com/

< HTTP/1.1 406 Not Acceptable
< Content-Length: 195
< Content-Type: application/json; charset=utf-8
< 
{
    "httpCode": 406,
    "message": "This resource can not respond with a format the client will find acceptable. This resource supports: [application\/json, application\/xml, text\/html]."
}

如果无法确定异常的错误代码,则使用默认的500错误代码。根据需要将添加更多HttpException类。

许可证

MIT许可证(MIT)

版权所有(c)2012-2014 Vic Cherubini,Bright March,LLC