happyr / json-api-response-factory

符合apijson规范的响应工厂

0.6.0 2023-07-19 17:50 UTC

This package is auto-updated.

Last update: 2024-08-28 05:19:20 UTC


README

Latest Version Software License Total Downloads

一个围绕 league/fractal 的小型包装器,用于支持 JsonApi 错误和成功响应。

安装

composer require happyr/json-api-response-factory

用法

ResponseFactory 可以用于创建单个对象、对象集合或自定义响应。

转换器

响应中使用的每个对象都需要一个实现了 Happyr\JsonApiResponseFactory\Transformer\AbstractTransformer 的转换器

use Happyr\JsonApiResponseFactory\Transformer\AbstractTransformer;

final class FooTransformer extends AbstractTransformer
{
   public function getResourceName(): string
   {
       return 'foo';
   }

   public function transform(Foo $item): array
   {
       return [
           'id' => $item->getId(),
           'bar' =>  (string)$item->getBar(),
       ];
   }
}

包含单个项的响应

$item = new Foo('bar');
$response = $responseFactory->createWithItem($item, new FooTransformer());

响应将看起来像这样

{
    "data": {
        "type": "foo",
        "id": "1",
        "attributes": {
            "bar": "bar"
        }
    }
}

包含项目集合的响应

$items = [
    new Foo('bar'),
    new Foo('baz'),
];
$response = $responseFactory->createWithCollection($items, new FooTransformer());

响应将看起来像这样

{
    "data": [
        {
            "type": "foo",
            "id": "1",
            "attributes": {
                "bar": "bar"
            }
        },
        {
            "type": "foo",
            "id": "2",
            "attributes": {
                "bar": "baz"
            }
        }
    ]
}

自定义响应

要使用 ResponseFactory 响应创建带有自定义有效负载/状态码的响应,你应该创建一个实现 Happyr\JsonApiResponseFactory\ResponseModelInterface 的类

use Happyr\JsonApiResponseFactory\ResponseModelInterface;

final class InvalidRequestResponseModel implements ResponseModelInterface
{
   public function getHttpStatusCode() : int
    {
        return 400;
    }

    public function getPayload() : array
    {
        return [
            'error' => 'Invalid request.',
        ];
    }
}

并将其传递给响应工厂

$model = new InvalidRequestResponseModel();
$response = $responseFactory->createWithResponseModel($model);

响应将看起来像这样

{
    "error": "Invalid request."
}

src/Model/ 中有用于通常消息响应(接受、创建等)和符合 json-api 错误标准的错误响应的模型,您可以使用它们,或者借鉴我们使用库的方式,编写您自己的模型。

消息的示例响应

{
    "meta": {
        "message": "Accepted"
    }
}

验证失败时的示例响应

{
  "errors": [
    {
      "status": "400",
      "title": "Validation failed",
      "detail": "This value should not be blank.",
      "source": {
        "parameter": "foo",
      },
      "links": {
        "about": "http://docs.docs/errors/missing-parameter"
      }
    },
    {
      "status": "400",
      "title": "Validation failed",
      "detail": "This value has to be larger than 30.",
      "source": {
        "parameter": "bar",
      },
      "links": {
        "about": "http://docs.docs/errors/range"
      }
    }
  ]
}