rekhyt / dto
使用 JSON Schema 规范来定义数据传输对象 (DTOs)
v1.0.0
2020-06-04 12:14 UTC
Requires
- php: >=5.6
- pimple/pimple: ^3.0
Requires (Dev)
- mockery/mockery: ^0.9.7
- phpunit/phpunit: 5.7.8
This package is auto-updated.
Last update: 2024-09-04 23:04:11 UTC
README
此包提供了一个快速定义结构化对象 (DTOs) 的方法,使用的是 JSON Schema 标准。
数据传输对象 (DTO) 是一个用于在应用程序的不同层之间传递类型化数据的对象,在概念上类似于 C 语言中的 Structs,Martin Fowler 的 Transfer Objects 或 Value Objects。
DTOs 是数据访问对象 (DAO) 或 Repository 模式的有益补充。
该功能类似于 shape 包提供的功能。
示例
使用 JSON Schema 语法定义 PHP 对象
<?php class ExampleObject extends Dto\Dto { protected $schema = [ 'type' => 'object', 'properties' => [ 'a' => ['type' => 'string'], 'b' => ['type' => 'integer'] ], 'additionalProperties' => false ]; }
现在您可以实例化并使用您的对象
<?php // Assume you have included vendor/autoload.php and the above ExampleObject class $obj = new ExampleObject(); $obj->a = "Some String"; $obj->b = 123; // this is defined as an integer, so values WILL be type-cast to integer! $obj->c = 'Whoops, this will throw an Exception because additionalProperties are not allowed';
或直接引用 JSON Schema
<?php class ExampleObject extends Dto\Dto { protected $schema = [ '$ref' => 'http://example.com/some/schema.json' ]; }
可能的用途
- 在 API 中:在运行时消费 JSON Schema API,无需解析数据格式。
- 在视图层:您可以使用 DTO 定义而不是传递任意数组,并使用类型提示来确保视图始终拥有它们所需的数据属性。
- 用于缓存:您可以使用特定的 DTO 类存储和检索缓存,而不必猜测哪些属性或数组键可用。
- 服务类:当您的服务类期望操作特定类型的数据时。
- 结果集:从数据库查找返回一个 stdClass 对象数组或关联数组,而不是 DTO。
在 DTO Wiki 中阅读更多内容
待办事项
- 属性依赖关系 https://spacetelescope.github.io/understanding-json-schema/reference/object.html
- 模式依赖关系(扩展模式)
- 其他 JSON Schema 版本的空间(v5 即将推出!)
版本历史
3.2.7
- 修复了当使用
$ref
关键字在模式中引用 PHP 类时的验证问题。
3.2.6
- 删除了未使用的依赖项
webmozart/json
。
3.2.4
- 通过消除冗余验证提高了性能。
3.2.3
__toString()
方法中的strval()
转换:当检查对象属性时,这为 UX 提供了便利。
3.2.2
- 支持读取 JSON 模式时嵌套相对模式路径。
3.2.1
- 为
serialize
方法添加了测试。
3.2.0
- 包括
$baseDir
和getBaseDir()
方法,以支持使用$ref
关键字引用 JSON 模式的相对路径。
3.1.0
- 包括对内联定义及其继承的正确支持。
3.0.0
- 集成 JSON Schema 4 规范来驱动所有结构和类型定义。
2.0.0
我们不提版本 2。
1.0.8
- 修复了注入到构造函数中的 DTO 匿名散列的问题。
- 修复了测试中的命名空间问题。
1.0.7
修复了将 DTO 数组注入构造函数作为数组的问题。
1.0.6
修复了注入到构造函数中的层次结构数据。
1.0.5
首次发布,添加了一些整理作为文档。