Fill Plain Old PHP Object with JSON content.
You can install this library with Composer:
composer require abgeo/json-to-popo
Include composer autoloader in your main file (Ex.: index.php)
require __DIR__.'/../vendor/autoload.php';
Consider that you have example.json
with the following content:
{
"firstName": "Temuri",
"lastName": "Takalandze",
"active": true,
"position": {
"title": "Developer",
"department": {
"title": "IT"
}
}
}
and several POPO classes to represent this JSON data:
Department.php
<?php
class Department
{
/**
* @var string
*/
private $title;
// Getters and Setters here...
}
Position.php
<?php
class Position
{
/**
* @var string
*/
private $title;
/**
* @var ABGEOPOPOExampleDepartment
*/
private $department;
// Getters and Setters here...
}
Person.php
<?php
class Person
{
/**
* @var string
*/
private $firstName;
/**
* @var string
*/
private $lastName;
/**
* @var bool
*/
private $active;
/**
* @var ABGEOPOPOExamplePosition
*/
private $position;
// Getters and Setters here...
}
Note: All POPO properties must have full qualified @var
annotation with the correct data type.
Now you want to convert this json to popo with relations. This package gives you this ability.
Let's create new ABGEOPOPOComposer
object and read example.json
content:
$composer = new Composer();
$jsonContent = file_get_contents(__DIR__ . '/example.json');
Time for magic! Call composeObject()
with the contents of JSON and the main class, and this will give you POPO:
$resultObject = $composer->composeObject($jsonContent, Person::class);
Print $resultObject
:
var_dump($resultObject);
//class ABGEOPOPOExamplePerson#2 (4) {
// private $firstName =>
// string(6) "Temuri"
// private $lastName =>
// string(10) "Takalandze"
// private $active =>
// bool(true)
// private $position =>
// class ABGEOPOPOExamplePosition#4 (2) {
// private $title =>
// string(9) "Developer"
// private $department =>
// class ABGEOPOPOExampleDepartment#7 (1) {
// private $title =>
// string(2) "IT"
// }
// }
//}
See full example here.
Please see CHANGELOG for details.
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
Copyright © 2020 Temuri Takalandze.
Released under the MIT license.