mk / hal
HAL标准的实现,用于REST API响应或类似场景
2.0.1
2019-02-04 16:00 UTC
Requires (Dev)
- phpunit/phpunit: ^7
This package is auto-updated.
Last update: 2024-09-05 04:40:28 UTC
README
此存储库仍处于早期开发阶段。如果您发现任何问题或缺少任何功能,请随时提出问题。
MKHal 是用 PHP 编写的 HAL 规范实现。它可以用来构建 HAL 特定的数据结构并将其转换为 JSON 或 XML。它可以轻松集成到您的当前 API 后端工作流程中。
要求
- PHP 7.0 或更高版本
安装
您可以克隆或下载此包,并在项目中使用它,或者只需通过 composer 安装它
composer require mk/hal
用法
对象类型
MKHal 提供不同类型的类来表示典型的 HAL 实现结构
- HALObject:
HALObject类代表 HAL 规范中的主要资源。它可以包含普通数据、HALLink对象和HALCurie对象。它还可以通过标签嵌入额外的HALObjects。 - HALLink:
HALLink类代表 HAL 文档中 _links 部分中的典型链接资源。它可以包含不同的信息,如 href 属性。它将自动序列化并与HALObject实例一起序列化。一个HALObject可以在标签后包含额外的链接。 - HALCurie:
HALCurie类是 HAL 中 curies 属性的表示。一个HALObject实例可以包含多个 curies。
基本用法
use MK\HAL\HALObject; use MK\HAL\HALLink; use MK\HAL\HALCurie; $hal = new HALObject('/orders'); $hal->addData(array( "offers" => 5, "prices" => array( "normal" => "10.99", "season" => "5.99" ) )); $hal->addCurie(new HALCurie('ea', 'http://example.com/docs/rels/{rel}')); $hal->addLink('next', new HALLink('/orders?page=2')); $hal->addLinkCollection('ea:admin', array( new HALLink('/admin/2'), new HALLink('/admin/5') )); $product = new HALObject('/product/1'); $product->addLink('next', new HALLink('/product/2')); $hal->embed('product', $product); $hal->embedCollection('coupon', array( new HALObject('/coupon/5'), new HALObject('/coupon/6') )); // use export() for json serialization echo $hal->export(); // calls json_encode internally // or simple encode the HALObject echo json_encode($hal);
调用 export() 方法将创建 HAL 规范的 JSON 表示形式
{
"_links": {
"self": {
"href": "/orders"
},
"curies": [
{
"name": "ea",
"href": "http://example.com/docs/rels/{rel}",
"templated": true
}
],
"next": {
"href": "/orders?page=2"
},
"ea:admin": [
{
"href": "/admin/2"
},
{
"href": "/admin/5"
}
]
},
"offers": 5,
"prices": {
"normal": "10.99",
"season": "5.99"
},
"_embedded": {
"product": {
"_links": {
"self": {
"href": "/product/1"
},
"next": {
"href": "/product/2"
}
}
},
"coupon": [
{
"_links": {
"self": {
"href": "/coupon/5"
}
}
},
{
"_links": {
"self": {
"href": "/coupon/6"
}
}
}
]
}
}
路线图
- 实现基本 HAL 规范
- 启用 curies
- 良好的类层次结构
- JSON 导出/输出
- 从给定对象自动创建 HAL 数据
- XML 导出/输出
- 读取 HAL 对象以将库用作客户端
- Slim 框架集成