Rellene un objeto PHP antiguo y simple con contenido JSON.
Puedes instalar esta biblioteca con Composer:
composer require abgeo/json-to-popo
Incluya el cargador automático del compositor en su archivo principal (Ej.: index.php)
require __DIR__.'/../vendor/autoload.php';
Considera que tienes example.json
con el siguiente contenido:
{
"firstName" : " Temuri " ,
"lastName" : " Takalandze " ,
"active" : true ,
"position" : {
"title" : " Developer " ,
"department" : {
"title" : " IT "
}
}
}
y varias clases POPO para representar estos datos JSON:
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...
}
Nota : Todas las propiedades POPO deben tener una anotación @var
completa con el tipo de datos correcto.
Ahora desea convertir este json to popo con relaciones. Este paquete le brinda esta capacidad.
Creemos un nuevo objeto ABGEOPOPOComposer
y leamos el contenido example.json
:
$ composer = new Composer ();
$ jsonContent = file_get_contents ( __DIR__ . ' /example.json ' );
¡Hora de la magia! Llama composeObject()
con el contenido de JSON y la clase principal, y esto te dará POPO:
$ resultObject = $ composer -> composeObject ( $ jsonContent , Person::class);
Imprimir $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"
// }
// }
//}
Vea el ejemplo completo aquí.
Consulte CHANGELOG para obtener más detalles.
Las solicitudes de extracción son bienvenidas. Para cambios importantes, primero abra un problema para discutir lo que le gustaría cambiar.
Asegúrese de actualizar las pruebas según corresponda.
Copyright © 2020 Temuri Takalandze.
Publicado bajo la licencia MIT.