百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
Y

yang

> 开发工具
开源

适用于 PHP 的高效、精美的、符合 PSR-7 标准的 JSON:API 1.1 客户端库

170 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

适用于 PHP 的高效、精美的、符合 PSR-7 标准的 JSON:API 1.1 客户端库

Woohoo Labs. Yang

[Latest Version on Packagist][link-version] Software License [![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.

Table of Contents

  • Introduction
    • Features
  • Install
  • Basic Usage
    • Request builder
    • HTTP clients
    • Response
    • Hydration
  • Advanced Usage
    • Custom serialization
    • Custom deserialization
  • Versioning
  • Change Log
  • Contributing
  • Support
  • Credits
  • License

Introduction

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.

Features

  • 100% PSR-7 compatibility
  • 99% JSON:API 1.1 conformance (approximately)
  • Provides a Request Builder to setup JSON:API request more easily
  • Provides easy-to-use HTTP clients via PSR-18 and HTTPlug
  • Supports hydrators out-of-the-box in order to easily convert API responses to objects

Install

The only thing you need before getting started is Composer.

Install an HTTP client and message implementations:

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:

bash
$ composer require php-http/guzzle7-adapter

Install Yang:

To install the latest version of this library, run the command below:

bash
$ composer require woohoolabs/yang

Note: The tests and examples won't be downloaded by default. You have to use composer require woohoolabs/yang --prefer-source or clone the repository if you need them.

Yang requires PHP 7.4 at least. You may use Yang 2.3 for PHP 7.2.

Basic Usage

Yang can help you in three ways to communicate with JSON:API servers. The following subsections will cover these topics.

Request builder

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:

php
$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");

HTTP clients

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.

Response

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:

php
// 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:

…

Hydration

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:

php
$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:

php
// 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:

php
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() throws DocumentException when 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 - an stdObject along with all the attributes and relationships is returned.

Additionally, you may use the ClassHydrator::hydrateCollection() method for retrieving many dogs:

php
// 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() throws DocumentException when the primary data is a single resource. Otherwise - when the primary data is a collection of resources - an array of stdObjects 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 single stdClass if the primary data is a single resource. Otherwise - when the primary data is a collection of resources - an array of stdObjects is returned.

Advanced Usage

Custom serialization

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:

php
// 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.

Custom deserialization

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:

php
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:

php
// 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.

Examples

Have a look at the examples directory for a really basic example.

Versioning

This library follows SemVer v2.0.0.

Change Log

Please see CHANGELOG for more information what has changed recently.

Testing

Woohoo Labs. Yang has a PHPUnit test suite. To run the tests, run the following command from the project folder:

bash
$ phpunit

Additionally, you may run docker-compose up or make test in order to execute the tests.

Contributing

Please see CONTRIBUTING for details.

Support

Please see SUPPORT for details.

Credits

  • [Máté Kocsis][link-author]
  • [All Contributors][link-contributors]

License

The MIT License (MIT). Please see the License File for more information.

Issues· 5 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPclientjson-apiphppsr-7

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类开发工具
定价开源

> 相关工具

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具