psx/nested

从关系数据库构建复杂的嵌套数据结构

v0.1.2 2024-07-21 21:15 UTC

This package is auto-updated.

Last update: 2024-09-21 21:42:10 UTC


README

关于

这个库帮助基于关系表构建复杂的嵌套JSON响应。

基本用法

在核心,这个库提供了一个Builder类,允许你定义一个结构,说明你的JSON响应结果应该如何呈现。以下代码来自我们的测试案例,应该能让你对如何生成复杂的JSON结构有一个初步的了解。

<?php

$connection = null; // a doctrine DBAL connection
$builder = new \PSX\Nested\Builder($connection);

$definition = [
    'totalResults' => $builder->doValue('SELECT COUNT(*) AS cnt FROM psx_sql_provider_news', [], $builder->fieldInteger('cnt')),
    'entries' => $builder->doCollection('SELECT * FROM psx_sql_provider_news ORDER BY id DESC', [], [
        'id' => $builder->fieldInteger('id'),
        'title' => $builder->fieldCallback('title', function($title){
            return ucfirst($title);
        }),
        'author' => $builder->doEntity('SELECT * FROM psx_sql_provider_author WHERE id = ?', [new Reference('author_id')], [
            'id' => $builder->fieldFormat('id', 'urn:profile:%s'),
            'name' => 'name',
            'uri' => 'uri',
        ]),
        'tags' => $builder->doColumn('SELECT title FROM psx_sql_provider_news', [], 'title'),
        'date' => $builder->fieldDateTime('create_date'),
    ])
];

$result = $builder->build($definition);

echo \json_encode($result);

这将产生以下JSON有效载荷

{
  "totalResults": 2,
  "entries": [
    {
      "id": 2,
      "title": "Bar",
      "author": {
        "id": "urn:profile:1",
        "name": "Foo Bar",
        "uri": "https:\/\/phpsx.org"
      },
      "tags": [
        "foo",
        "bar"
      ],
      "date": "2016-03-01T00:00:00Z"
    },
    {
      "id": 1,
      "title": "Foo",
      "author": {
        "id": "urn:profile:1",
        "name": "Foo Bar",
        "uri": "https:\/\/phpsx.org"
      },
      "tags": [
        "foo",
        "bar"
      ],
      "date": "2016-03-01T00:00:00Z"
    }
  ]
}

JSON定义

也可以用JSON注释来声明定义

{
  "totalEntries": {
    "$value": "SELECT COUNT(*) AS cnt FROM psx_sql_provider_news",
    "$definition": {
      "$key": "cnt",
      "$field": "integer"
    }
  },
  "entries": {
    "$collection": "SELECT id, author_id, title, create_date FROM psx_sql_provider_news ORDER BY id ASC LIMIT :startIndex, 8",
    "$params": {
      "startIndex": 0
    },
    "$definition": {
      "id": {
        "$key": "id",
        "$field": "integer"
      },
      "title": "title",
      "tags": {
        "$column": "SELECT title FROM psx_sql_provider_news",
        "$definition": "title"
      },
      "author": {
        "$entity": "SELECT id, name, uri FROM psx_sql_provider_author WHERE id = :id",
        "$params": {
          "id": {
            "$ref": "author_id"
          }
        },
        "$definition": {
          "displayName": "name",
          "uri": "uri"
        }
      }
    }
  }
}

然后你可以通过JSON提供者执行这个JSON定义

<?php

$json = '{}'; // JSON from above

$provider = new JsonProvider($this->connection);
$result = $provider->create(\json_decode($json));

echo \json_encode($result);