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?

2
  • possible duplicate of Convert Array to Object PHP Commented Jan 5, 2014 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. Commented Jan 6, 2014 at 14:54

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.