enm/json-api-client

json api 规范 (jsonapi.org) 的客户端 PHP 实现

4.0.1 2020-03-25 14:17 UTC

This package is auto-updated.

Last update: 2024-09-21 23:50:48 UTC


README

Build Status

json api 规范的客户端 PHP 实现。

安装

composer require enm/json-api-client

建议安装 kriswallsmith/buzz 作为 HTTP 客户端,并安装 nyholm/psr7 作为 HTTP 工厂。

composer require kriswallsmith/buzz nyholm/psr7

您也可以使用任何实现 PSR-18 的 HTTP 客户端。

使用方法

首先,您应该在 enm/json-api-common 阅读文档,其中定义了所有基本结构。

您的 API 客户端是 Enm\JsonApi\Client\JsonApiClient 的一个实例,它需要一个 PSR-18 HTTP 客户端(Psr\Http\Client\ClientInterface)来执行请求。

$client = new JsonApiClient(
    'http://example.com/api',
    $httpClient, // instance of Psr\Http\Client\ClientInterface
    $uriFactory, // instance of Psr\Http\Message\UriFactoryInterface
    $requestFactory, // instance of Psr\Http\Message\RequestFactoryInterface
    $streamFactory, // instance of Psr\Http\Message\StreamFactoryInterface
    new Serializer(),
    new Deserializer()
);

$request = $client->createGetRequest(new Uri('/myResources/1')); // will fetch the resource at http://example.com/api/myResources/1
$request->requestInclude('myRelationship'); // include a relationship

$response = $client->execute($request);

$document = $response->document();
$myResource = $document->data()->first(); // the resource fetched by this request
$myIncludedResources = $document->included()->all(); // the included resources fetched with the include parameter