optimus/architect

2.0.4 2023-12-28 14:51 UTC

This package is auto-updated.

Last update: 2024-08-28 16:11:41 UTC


README

Latest Version Software License Build Status Coverage Status Total Downloads

介绍

Architect 用于动态创建 API 资源关系的结构。听起来很复杂且自负吗?

想象你有一个资源 Book 以及相关的资源 Author

Book 1-----n Author

正常嵌入式模式

这是默认情况下使用嵌入式模式加载相关资源的方式。

{
   "books":[
      {
         "id":1,
         "author_id":1,
         "title":"How to save the world from evil",
         "pages":100,
         "author":{
            "id":1,
            "name":"Optimus Prime"
         }
      },
      {
         "id":2,
         "author_id":2,
         "title":"How to take over the world",
         "pages":100,
         "author":{
            "id":2,
            "name":"Megatron"
         }
      }
   ]
}

现在,使用 Architect 你可以使用 ids 模式和 sideloading 模式加载相关资源

Ids 模式

只加载相关资源的 IDs。使用 Eloquent 模型的主键属性正在计划中。查看详情。

{
   "books":[
      {
         "id":1,
         "author_id":1,
         "title":"How to save the world from evil",
         "pages":100,
         "author":1
      },
      {
         "id":2,
         "author_id":2,
         "title":"How to take over the world",
         "pages":100,
         "author":2
      }
   ]
}

Sideloading 模式

将相关资源提升到全局作用域,并使用 ID 模式解析器留下 IDs。

{
   "author":[
      {
         "id":1,
         "name":"Optimus Prime"
      },
      {
         "id":2,
         "name":"Megatron"
      }
   ],
   "books":[
      {
         "id":1,
         "author_id":1,
         "title":"How to save the world from evil",
         "pages":100,
         "author":1
      },
      {
         "id":2,
         "author_id":2,
         "title":"How to take over the world",
         "pages":100,
         "author":2
      }
   ]
}

使用方法

Architect 与常规数组(集合和资源)、Illuminate\Support\CollectionIlluminate\Database\Eloquent\Model 一起工作。

<?php

$books = Book::with('Author')->get();

$architect = new \Optimus\Architect\Architect;
$parsed = $architect->parseData($books, [
    'author' => 'sideload' // can also be embed or ids (embed is default)
], 'books');

Optimus\LaravelController 提供了方便的方法来在查询参数中定义 Architect 关系。

安装

composer require optimus/architect

标准

此包符合 PSR-1PSR-2PSR-4 标准。如果您发现不符合标准的地方,请通过 pull request 发送补丁。

测试

$ phpunit

贡献

有关详细信息,请参阅 CONTRIBUTING

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件