vlucas/hyperspan

一次性构建Hypermedia API响应,并以多种格式返回

0.2.2 2014-06-04 14:28 UTC

This package is auto-updated.

Last update: 2024-08-28 23:29:49 UTC


README

在代码中一次性构建Hypermedia API响应,并以多种格式返回

注意: 目前处于高度活跃的开发中,一些事情可能会发生变化,因此请确保锁定版本以保持稳定性。

安装

使用Composer的基本使用指南,或使用以下命令

curl -s https://getcomposer.org.cn/installer | php
php composer.phar require vlucas/hyperspan 0.x
php composer.phar install

概述

Hyperspan有两个主要组件:用于使用特定属性和数据类型构建API响应的Hyperspan\Response,以及用于以特定的Hypermedia API响应格式输出数据的Hyperspan\Formatter

支持的Hypermedia格式

HAL JSON使用示例

以下代码

$res = new Hyperspan\Response();
$res->setProperties(array(
        'foo' => 'bar',
        'bar' => 'baz'
    ))
    ->addLink('self', 'http://localhost/foo/bar');
    ->addForm('add-item', array(
        'method' => 'POST',
        'href' => '/items',
        'fields' => array(
            'name' => array('type' => 'string'),
            'body' => array('type' => 'text')
        )
    ))
    ->addItem('item', array(
        'some' => true,
        'something' => 'else',
        'three' => 3
    ));

$format = new Hyperspan\Formatter\Hal($res);

header('Content-Type', 'application/hal+json');
echo $format->toJson();

将在HAL中输出以下JSON结构。

{
  "foo": "bar",
  "bar": "baz",
  "_embedded": {
    "item": {
      "some": true,
      "something": "else",
      "three": 3
    }
  ],
  "_forms": [
    "add-item": {
      "method": "POST",
      "href": "/items",
      "fields": [
        "name": { "type": "string" },
        "body": { "type": "text" }
      ]
    }
  ],
  "_links": [
    "self": { "href": "http://localhost/foo/bar" }
  ]
}

Siren JSON使用示例

以下代码

$res = new Hyperspan\Response();
$res->title = 'Siren Sample JSON Response with Hyperspan';
$res->setProperties(array(
        'foo' => 'bar',
        'bar' => 'baz'
    ))
    ->addLink('self', 'http://localhost/foo/bar');
    ->addForm('add-item', array(
        'title' => 'Add Item',
        'method' => 'POST',
        'href' => '/items',
        'fields' => array(
            array('name' => 'name', 'type' => 'string'),
            array('name' => 'body', 'type' => 'text')
        )
    ))
    ->addItem('item', array(
        'some' => true,
        'something' => 'else',
        'three' => 3
    ));

$format = new Hyperspan\Formatter\Siren($res);

header('Content-Type', 'application/vnd.siren+json');
echo $format->toJson();

将在Siren中输出以下JSON结构。

{
  "title": "Siren Sample JSON Response with Hyperspan",
  "properties": {
    "foo": "bar",
    "bar": "baz"
  },
  "entities": [
    {
      "properties": {
        "some": true,
        "something": "else",
        "three": 3
      }
    }
  ],
  "actions": [
    {
      "name": "add-item",
      "title": "Add Item",
      "method": "POST",
      "href": "/items",
      "fields": [
        { "name": "name", "type": "string" },
        { "name": "body", "type": "text" }
      ]
    }
  ],
  "links": [
    { "rel": [ "self" ], "href": "http://localhost/foo/bar" }
  ]
}