Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat pattern should I use to convert PHP associative arrays to/from complex Object graphs?
    primarykey
    data
    text
    <p>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.</p> <p>I have these classes to model People in my application:</p> <pre><code>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; } </code></pre> <p>My data (in JSON) looks like this:</p> <pre><code>'person': { 'name': 'Joe', 'dogs': [ {'breed': 'Husky', 'color': 'Black'}, {'breed': 'Poodle', 'color': 'Yellow'} ] 'hobbies': [ {'description': 'Skiing', 'cost': 500}, {'description': 'Running', 'cost': 0} ] } </code></pre> <p>I can easily convert this JSON to an associative array using <code>json_decode</code>, but the difficulty comes in converting each of the nested <code>Hobby</code> and <code>Pet</code> objects into the appropriate classes, and then when I want the associative array back, converting these objects into associative arrays again.</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload