sarbinski / json-api
PHP 的响应 JSON API 库
0.1.1
2019-04-03 09:41 UTC
Requires
- php: >=5.4.0
This package is not auto-updated.
Last update: 2024-09-26 16:58:30 UTC
README
示例
示例 1 - 从数组创建 JSON API 数据对象
<?php require_once __DIR__ . '/vendor/autoload.php'; // Data loaded from database(for example) $data = [ ['id' => '1', 'name' => 'Foo'], ['id' => '2', 'name' => 'Bar'], ]; $api = new Sarbinski\JsonApi\Api(); $api->createData($dataObject, 'Sarbinski\JsonApi\Schemas\TestSchema'); echo $api->buildMainJSONStructure()->getPrintData(true);
将输出
{ "data": [ { "type": "test-schema", "id": "1", "attributes": { "name": "1_Foo" } }, { "type": "test-schema", "id": "2", "attributes": { "name": "2_Bar" } } ] }
TestSchema
是一个 适配器,用于提取给定实体的属性
<?php class TestSchema extends Schema { protected $type = 'test-schema'; public function getAttributes($resource) { return [ 'name' => $resource['id'] . '_' . $resource['name'], ]; } public function getId($resource) { return $resource['id']; } public function getRelationships($resource) { return false; } }
示例 2 - 从可遍历对象创建 JSON API 数据对象
我们再次使用 TestSchema
作为 Schema 适配器
<?php class DataClass implements Iterator { private $items = []; public function __construct() { $this->items = [ ['id' => 1, 'name' => 'a'], ['id' => 2, 'name' => 'b'], ]; } public function current() { return current($this->items); } public function key() { return key($this->items); } public function next() { return next($this->items); } public function rewind() { return reset($this->items); } public function valid() { return key($this->items) !== null; } } $dataObject = new DataClass(); $api->createData($dataObject, 'Sarbinski\JsonApi\Schemas\TestSchema'); echo $api->buildMainJSONStructure()->getPrintData(true);
将输出
{ "data": [ { "type": "test-schema", "id": 1, "attributes": { "name": "1_a" } }, { "type": "test-schema", "id": 2, "attributes": { "name": "2_b" } } ] }
Schema 类的自动加载
这个库与 PSR-4 兼容。您可以将您的 Schema 类放在任何地方,只要您已经注册了适当的自动加载即可。