abgeo / json-to-popo
用 JSON 内容填充普通的 PHP 对象。
v1.0.0
2020-05-03 14:30 UTC
Requires
- php: ^7.2
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^8.5
This package is auto-updated.
Last update: 2024-08-29 05:29:37 UTC
README
用 JSON 内容填充普通的 PHP 对象。
安装
您可以使用 Composer 安装此库
composer require abgeo/json-to-popo
用法
将 composer 自动加载器包含在主文件中(例如:index.php)
require __DIR__.'/../vendor/autoload.php';
假设您有一个 example.json
,其内容如下
{ "firstName": "Temuri", "lastName": "Takalandze", "active": true, "position": { "title": "Developer", "department": { "title": "IT" } } }
并有一些 POPO 类来表示这些 JSON 数据
Department.php
<?php class Department { /** * @var string */ private $title; // Getters and Setters here... }
Position.php
<?php class Position { /** * @var string */ private $title; /** * @var \ABGEO\POPO\Example\Department */ private $department; // Getters and Setters here... }
Person.php
<?php class Person { /** * @var string */ private $firstName; /** * @var string */ private $lastName; /** * @var bool */ private $active; /** * @var \ABGEO\POPO\Example\Position */ private $position; // Getters and Setters here... }
注意:所有 POPO 属性必须具有完全限定的 @var
注释和正确的数据类型。
现在您想将此 JSON 转换为具有关系的 POPO。此包提供了这种能力。
让我们创建一个新的 ABGEO\POPO\Composer
对象并读取 example.json
的内容
$composer = new Composer(); $jsonContent = file_get_contents(__DIR__ . '/example.json');
魔法时间!使用 JSON 内容和主类调用 composeObject()
,这将为您提供 POPO
$resultObject = $composer->composeObject($jsonContent, Person::class);
打印 $resultObject
var_dump($resultObject); //class ABGEO\POPO\Example\Person#2 (4) { // private $firstName => // string(6) "Temuri" // private $lastName => // string(10) "Takalandze" // private $active => // bool(true) // private $position => // class ABGEO\POPO\Example\Position#4 (2) { // private $title => // string(9) "Developer" // private $department => // class ABGEO\POPO\Example\Department#7 (1) { // private $title => // string(2) "IT" // } // } //}
请参阅完整的示例 这里。
变更日志
请参阅 CHANGELOG 了解详细信息。
贡献
欢迎拉取请求。对于重大更改,请先提出一个问题以讨论您想更改的内容。
请确保根据需要更新测试。
作者
- Temuri Takalandze - 初始工作
许可证
版权所有 © 2020 Temuri Takalandze。
在 MIT 许可下发布。