适用于 PHP 的高效、精美的、符合 PSR-7 标准的 JSON:API 1.1 客户端库
[][link-version]
[![Build Status][ico-build]][link-build]
[![Coverage Status][ico-coverage]][link-coverage]
[![Quality Score][ico-code-quality]][link-code-quality]
[![Total Downloads][ico-downloads]][link-downloads]
[![Gitter][ico-support]][link-support]
Woohoo Labs. Yang is a PHP framework which helps you to communicate with JSON:API servers more easily.
JSON:API specification reached 1.0 on 29th May 2015 and we also believe it is a big day for RESTful APIs as this specification makes APIs more robust and future-proof than they have ever been. Woohoo Labs. Yang (named after Yin-Yang) was born to bring efficiency and elegance to your JSON:API clients, while Woohoo Labs. Yin is its server-side counterpart.
The only thing you need before getting started is Composer.
Because Yang requires a HTTP client implementation, you must install one first. You may use Guzzle 7 Adapter or any other library of your preference:
$ composer require php-http/guzzle7-adapterTo install the latest version of this library, run the command below:
$ composer require woohoolabs/yangNote: The tests and examples won't be downloaded by default. You have to use
composer require woohoolabs/yang --prefer-sourceor clone the repository if you need them.
Yang requires PHP 7.4 at least. You may use Yang 2.3 for PHP 7.2.
Yang can help you in three ways to communicate with JSON:API servers. The following subsections will cover these topics.
Yang comes with a powerful request builder with which you are able to setup PSR-7 Request objects in a JSON:API compliant way.
For this purpose, you may use the JsonApiRequestBuilder class as it can be seen in the following example.
…If you do not want to use the built-in Request Builder, you can freely setup any PSR-7 RequestInterface instances
in order to proceed with the next steps:
$request = new Request('GET', '');
$request = $request
->withProtocolVersion("1.1")
->withUri(new Uri("https://example.com/api/users?fields[users]=first_name,last_name"))
->withHeader("Accept", "application/vnd.api+json")
->withHeader("Content-Type", "application/vnd.api+json");The library comes with support for PSR-18 and HTTPlug,
so you can choose how you want to send your requests. If you installed the php-http/guzzle6-adapter package, then you
will be able to use Guzzle to do so:
…Of course, you can use any available HTTP Clients or create a custom HTTP Client thanks to PSR-18 and HTTPlug.
As soon as you have retrieved the server response, you can start querying it. Yang uses the PSR-7 compatible
JsonApiResponse class for this purpose. If you used a HTTP client introduced above, you will automatically
get an object of this type, otherwise you have to take care of instantiating it with the right dependencies:
// Instantiate a JSON:API response object from a PSR-7 response object with the default deserializer
$response = new JsonApiResponse($psr7Response);The JsonApiResponse class - above the ones defined by PSR-7 - has some methods to make the handling of JSON:API
responses easier:
…The Document class has various methods too:
…The DocumentLinks class features the following methods:
…The Error class has the following methods:
…The ResourceObject class has the following methods:
…The Relationship object supports the following methods:
…JSON:API responses with many related resources are not easily to process with the above approach. For example, if you want to retrieve the value of an attribute of a related resource, you need the following code:
$dogResource = $response->document()->primaryResource();
$breedName = $dogResource->relationship("breed")->resource()->attribute("name");This is a bit too much code to write, and it gets a lot worse when you want to map complex response documents with many relationships to objects:
…This is the situation when using a hydrator can help you. Currently, Yang has only one hydrator, the ClassDocumentHydrator which - if the
response was successful - maps the specified document to an stdClass along with all the resource attributes and relationships.
It means that errors, links, meta data won't be present in the returned object. However, relationships are very easy to
access now.
Let's use the document from the last example for demonstrating the power of hydrators:
// Check if hydration is possible
if ($document->hasAnyPrimaryResources() === false) {
return;
}
// Hydrate the document to an stdClass
$hydrator = new ClassDocumentHydrator();
$dog = $hydrator->hydrateSingleResource($response->document());That's all you need to do in order to create the same $dog object as in the first example! Now, you can display its properties:
echo "Dog:\n";
echo "Name : " . $dog->name . "\n";
echo "Breed: " . $dog->breed->name . "\n\n";
echo "Owners:\n";
foreach ($dog->owners as $owner) {
echo "Name : " . $dog->owner->name . "\n";
echo "Address: " . $dog->owner->address->city . ", " . $dog->owner->address->addressLine . "\n";
echo "------------------\n";
}Note: The method
ClassDocumentHydrator::hydrateSingleResource()throwsDocumentExceptionwhen the document doesn't have any primary data or if the primary data is a collection. Otherwise - when the primary data is a single resource - anstdObjectalong with all the attributes and relationships is returned.
Additionally, you may use the ClassHydrator::hydrateCollection() method for retrieving many dogs:
// Check if hydration is possible
if ($document->isSingleResourceDocument()) {
return;
}
// Hydrate the document to an array of stdClass
$hydrator = new ClassDocumentHydrator();
$dogs = $hydrator->hydrateCollection($response->document());Note: The method
ClassHydrator::hydrateCollection()throwsDocumentExceptionwhen the primary data is a single resource. Otherwise - when the primary data is a collection of resources - an array ofstdObjects along with all the attributes and relationship is returned.
Furthermore, there is a hydrate() method available for you when you don't care if the primary data is a single resource
or a collection of resources.
Note: The method
ClassDocumentHydrator::hydrate()returns an empty array when the document doesn't have any primary data. It returns an array containing a singlestdClassif the primary data is a single resource. Otherwise - when the primary data is a collection of resources - an array ofstdObjects is returned.
Sometimes you might need to be tricky to serialize the request body in a custom way. For example, if you dispatch a server request internally (within the original request), then you can send the request body as an array thanks to this feature - so you don't need to serialize at client-side and then deserialize at server-size. If you use Woohoo Labs. Yin and a custom deserializer at server-side, then this is an easy task to do.
At client-side, if you use Yang with the Request Builder, then you only have to pass a second constructor argument to it like below to take advantage of custom serialization:
// Instantiate a PSR-7 request
$request = new Request();
// Instantiate your custom serializer
$mySerializer = new MyCustomSerializer();
// Instantiate the request builder with a custom serializer
$requestBuilder = new JsonApiRequestBuilder($request, $mySerializer);You only have to make sure that your custom serializer implements the SerializerInterface.
Sometimes you might need to be tricky to deserialize a server response in a custom way. For example, if you dispatch a server request internally (within the original request), then you can receive the response body as an array thanks to this feature - so you don't need to serialize at server-side and then deserialize at client-size. If you use Woohoo Labs. Yin and a custom serializer at server-side, then this is an easy task to do.
At client-side, if you use Yang with the default HTTP Clients then you only have to pass a second constructor argument to them like below to take advantage of custom deserialization:
use Http\Adapter\Guzzle7\Client;
// Instantiate the Guzzle HTTP Client
$guzzleClient = Client::createWithConfig([]);
// Instantiate your custom deserializer
$myDeserializer = new MyCustomDeserializer();
// Instantiate the syncronous JSON:API Client with a custom deserializer
$syncClient = new JsonApiClient($guzzleClient, $myDeserializer);
// Instantiate the asyncronous JSON:API Client with a custom deserializer
$asyncClient = new JsonApiAsyncClient($guzzleClient, $myDeserializer);Otherwise pass your deserializer to the JsonApiResponse as its second argument like below:
// Instantiate a JSON:API response from a PSR-7 response with a custom deserializer
$response = new JsonApiResponse($psr7Response, new MyCustomDeserializer());You only have to make sure that your custom deserializer implements the DeserializerInterface.
Have a look at the examples directory for a really basic example.
This library follows SemVer v2.0.0.
Please see CHANGELOG for more information what has changed recently.
Woohoo Labs. Yang has a PHPUnit test suite. To run the tests, run the following command from the project folder:
$ phpunitAdditionally, you may run docker-compose up or make test in order to execute the tests.
Please see CONTRIBUTING for details.
Please see SUPPORT for details.
The MIT License (MIT). Please see the License File for more information.
暂无开放 Issues,或尚未同步最近议题。