oop - What pattern should I use to convert PHP associative arrays to/from complex Object graphs? -
my data arrives in form of associative arrays. works, code mess of nested arrays , start using proper oo/objects make data easier work with. cannot change way receive data, find clean way convert associative arrays instances of classes below.
i have these classes model people in 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 this:
'person': { 'name': 'joe', 'dogs': [ {'breed': 'husky', 'color': 'black'}, {'breed': 'poodle', 'color': 'yellow'} ] 'hobbies': [ {'description': 'skiing', 'cost': 500}, {'description': 'running', 'cost': 0} ] }
i can convert json associative array using json_decode
, difficulty comes in converting each of nested hobby
, pet
objects appropriate classes, , when want associative array back, converting these objects associative arrays again.
i can writing to/from array function in each of classes seems rather messy , prone error. there more straightforward way can hydrate/dehydrate these objects?
add hobby
public function fromarray($array){ if(isset($array['description'])){ $this->_description = $array['description']; } if(isset($array['cost'])){ $this->_cost = $array['cost']; } } public function toarray(){ $array = array(); $array['description'] = $this->_description; $array['cost'] = $this->_cost; return $array; }
and dog:
public function fromarray($array){ if(isset($array['breed'])){ $this->_breed = $array['breed']; } if(isset($array['cost'])){ $this->_cost = $array['color']; } } public function toarray(){ $array = array(); $array['breed'] = $this->_breed; $array['color'] = $this->_color; return $array; }
and in person class:
public function fromarray($array){ if(isset($array['name'])){ $this->_name = $array['name']; } if(isset($array['dogs'])){ foreach($array['dogs'] $dogarray){ $dog = new dog(); $dog->fromarray($dogarray); $this->_dogs[] = $dog; } } if(isset($array['hobbies'])){ foreach($array['hobbies'] $hobbyarray){ $hobby = new hobby(); $hobby->fromarray($hobbyarray); $this->_hobbies[] = $hobby; } } } public function toarray(){ $array = array(); $array['name'] = $this->_name; foreach($this->_dogs $dogobj){ $array['dogs'][] = $dogobj->toarray();; } foreach($this->_hobbies $hobbyobj){ $array['hobbies'][] = $hobbyobj->toarray();; } return $array; }
Comments
Post a Comment