My data arrives in the form of associative arrays. This works, but my code is a mess of nested arrays and I would like to start using proper OO/Objects to make this data easier to work with. I cannot change the way I receive this data, so I would like to find a clean way to convert the associative arrays into instances of my classes below.
I have these classes to model People in my application:
class Person {
/**
* @var string
*/
private $_name;
/**
* @var array[Dog]
*/
private $_dogs = array();
/**
* @var array[Hobby]
*/
private $_hobbies = array();
}
class Dog {
/**
* @var string
*/
private $_color;
/**
* @var string
*/
private $_breed;
}
class Hobby {
/**
* @var string
*/
private $_description;
/**
* @var int
*/
private $_cost;
}
My data (in JSON) looks like this:
'person': {
'name': 'Joe',
'dogs': [
{'breed': 'Husky', 'color': 'Black'},
{'breed': 'Poodle', 'color': 'Yellow'}
]
'hobbies': [
{'description': 'Skiing', 'cost': 500},
{'description': 'Running', 'cost': 0}
]
}
I can easily convert this JSON to an associative array using json_decode
, but the difficulty comes in converting each of the nested Hobby
and Pet
objects into the appropriate classes, and then when I want the associative array back, converting these objects into associative arrays again.
I can do all this by writing a to/from array function in each of my classes but that seems rather messy and prone to error. Is there a more straightforward way that I can quickly hydrate/dehydrate these objects?