Array to object conversion library. Convert a array to a object using simple and common property annotations
- Install composer
- Execute:
composer require rafrsr/lib-array2object
Only need the class with common annotations
<?php
class Player
{
/** @var string */
protected $name;
/** @var integer */
protected $number;
//setters and getters here
}
To use:
$phpArray = ['name' => 'David', 'number' => '1'];
$object = Array2ObjectBuilder::create()->build()->createObject(Player::class, $phpArray);
echo $object->getName();//David
echo $object->getNumber();//1
$array = Object2ArrayBuilder::create()->build()->createArray($object);
echo $array['name'];//David
echo $array['number'];//1
This library can be used to serialize/deserialize objects without a complex configuration.
//deserialize
$json = '{"name":"David","number"=>"1"}';
$object = Array2ObjectBuilder::create()->build()->createObject(Team::class, json_decode($json, true));
echo $object->getName()//David
//serialize
$array = Object2ArrayBuilder::create()->build()->createArray($object);
echo json_encode($array); // {"name":"David","number"=>"1"}
Using the library rafrsr/lib-array2xml is very handy convert from/to xml
//deserialize
$xml = '<Player><name>Player 1</name><number>1</number></Player>';
$object = Array2ObjectBuilder::create()->build()->create(Team::class, XML2Array::createArray($xml));
echo $object->getName()//David
//serialize
$array = Object2ArrayBuilder::create()->build()->createArray($object);
echo Array2XML::createXml('Player', $array); // '<Player><name>Player 1</name><number>1</number></Player>'
This library its handy to use and has some advanced configuration, but in some cases (need groups, versions and other stuffs) is required use advanced libraries like jms/serializer
Full documentation are available on the wiki page
This project is licensed under the MIT license.