kwai/jsonapi

PHP资源JSON:API序列化器

1.0.2 2021-12-26 13:46 UTC

This package is auto-updated.

Last update: 2024-09-26 20:46:38 UTC


README

Latest Stable Version PHP Version Require

使用PHP属性为PHP类提供JSON:API序列化器的库。

目前,此库不支持链接

安装

composer require kwai/jsonapi

要求

PHP属性用于将PHP类序列化为JSONAPI资源。因此,PHP版本必须至少为8.0。没有其他外部依赖。

文档

#[JSONAPI/Resource]

"JSONAPI/Resource"属性用于设置资源的类型。

  • 必须提供类型参数。
  • 此属性只能应用于类。
  • 默认情况下,id从id属性中检索。使用id参数使用具有其他名称的方法或属性。
use Kwai\JSONAPI;

#[JSONAPI/Resource(type: 'people')]
class Person 
{
    public function __construct(
        // We need at least an id property.
        private string $id,
    )
}

#[JSONAPI/Attribute]

"JSONAPI/Attribute"属性用于设置资源的属性。

  • 此属性可以应用于类的属性或方法。
  • 可以使用名称参数为属性命名。
  • 当应用于方法时,必须提供名称参数。
use Kwai\JSONAPI;

#[JSONAPI/Resource(type: 'people')]
class Person 
{
    public function __construct(
        private string $id,
        #[JSONAPI/Attribute]
        private string $name,
        private int $age,
    ) {
    }
    
    #[JSONAPI/Attribute(name: 'age')]
    public function getAge(): int
    {
        return $this->age;
    }
}

属性可以是私有的。方法必须是公开的。

具有如下Person实例

$person = new Person(
    id: '1',
    name: 'Jigoro Kano',
    age: 77,
);

结果将是

{
  "data": {
    "type": "people",
    "id": "1",
    "attributes": {
      "name": "Jigoro Kano",
      "age": 77
    }
  }
}

#[JSONAPI/Relationship]

"JSONAPI/Relationship"用于映射关系。

  • 此属性可以应用于属性或方法。
  • 可以使用名称参数为关系命名。
  • 如果没有设置名称参数的属性,将使用属性的名称。
  • 当应用于方法时,必须提供名称参数。
#[JSONAPI\Resource(type:'athletes')]
class Athlete
{
    public function __construct(
        private string $id,
        #[JSONAPI\Attribute]
        private string $name,
        #[JSONAPI\Relationship]
        private Country $country,
    ) {
    }
}

属性可以是私有的。方法必须是公开的。

关联的资源必须包含JSONAPI属性。如果不是,将抛出JSONAPI\Exception。关系也可以是数组。

使用以下PHP代码

$country = new Country(
    id: '1',
    code: 'BEL',
);
$athlete = new Athlete(
    id: '1',
    name: 'Ingrid Berghmans',
    country: $country
)

序列化结果将是

{
  "data": {
    "type": "athletes",
    "id": "1",
    "attributes": {
      "name": "Ingrid Berghmans"
    },
    "relationships": {
      "country": {
        "data": {
          "type": "countries",
          "id": "1"
        }
      }
    }
  },
  "included": [
    {
      "type": "countries",
      "id": "1",
      "attributes": {
        "code": "BEL"
      }
    }
  ]
}

序列化

JSONAPI\Document类用于将对象或数组序列化为JSON:API结构。

use Kwai\JSONAPI;

$person = new Person(
    id: '1',
    name: 'Jigoro Kano',
    age: 77,
);

try {
    $jsonapi = JSONAPI\Document::createFromObject($person)->serialize();
    // Send $jsonapi to the client...
} catch (JSONAPI\Exception $e) {
    // An exception occurred while serializing the PHP object.
}

元数据

可以使用setMeta方法设置元数据。

    try {
        $jsonapi =
            JSONAPI\Document::createFromObject($person)
                ->setMeta('count', 1)
                ->serialize();
    } catch (JSONAPI\Exception $e) {
        // Handle exception...
    }