0

I am writing a RESTful application using MongoDB as the DB. the php mongo driver returns query results as php arrays that, for all intents and purposes, look just like my class objects. Is it possible in php to cast the query results as a class object?

Similarly, can I cast a JSON decoded php array in the same way, even if it is missing a few properties?

Snowburnt
  • 6,523
  • 7
  • 30
  • 43
  • possible duplicate of [Convert Array to Object PHP](http://stackoverflow.com/questions/1869091/convert-array-to-object-php) – John Conde Jan 05 '14 at 17:17
  • @JohnConde I saw this, but it didn't look as specific as my question, I was looking for a way to convert it to a specific class while the question was looking to set it up as a generic object. – Snowburnt Jan 06 '14 at 14:54

1 Answers1

1

Well, you could cast it to stdClass:

$a = ['a' => 1, 'b' => 2];
$object = (object) $a;

But I guess you're not looking for that, you're probably trying to hydrate it.

In that case you could do something like this (assuming you're using public properties):

function castToObject(array $array, $className)
{
    $object = new $className();
    foreach ($array as $key => $val) {
        $object->$key = $val;
    }

    return $object;
}

Or if you're using get-set methods, change assignment line to:

$setter = 'set' . ucfirst($key);
$object->$setter($val);

Final implementation may vary. You have 3 options I can think about:

  1. Make all your model classes extend some base class which implements this functionality.
  2. Create a trait that implements it
  3. Create a wrapper around your connection that does this (I suggest this)

Trait would look something like this:

trait FromArrayTrait
{
    public static function fromArray(array $array)
    {
        $myClass = get_class();
        $object  = new $myClass(); 

        foreach ($array as $key => $val) {
            $object->$key = $val;
        }

        return $object;
    }
}

And in each model you could just:

class MyModel
{
    use FromArrayTrait;

    public $a;
    public $b;
}

And then in your logic:

$myArray = ['a' => 5, 'b' => 10];
$myModel = MyModel::fromArray($myArray);
Igor Pantović
  • 9,107
  • 2
  • 30
  • 43