Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a PHP Object Into a MONGO DB

Tags:

php

mongodb

I have a php object that I would like to store in my Mongo database. What is the best way to store the object in the database? I was thinking of looping over the object and creating an array but this is a complex object that has sub objects as well. Thanks

like image 460
gdoubleod Avatar asked Oct 20 '25 16:10

gdoubleod


1 Answers

The easiest way is probably to make your object "castable" to an array.

If the properties you want to store are public, you can just do:

$array = (array)$foo;

Otherwise, a toArray method, or making it implement an Iterator interface will work:

class Foo implements IteratorAggregate {

   protected $bar = 'hello';

   protected $baz = 'world';

   public function getIterator() {
       return new ArrayIterator(array(
           'bar' => $this->bar,
           'baz' => $this->baz,
       ));
   }

}

Obviously, you can also use get_object_vars, Reflection and such instead of hardcoding the property list in the getIterator method.

Then, just:

$foo = new Foo;
$array = iterator_to_array($foo);
$mongodb->selectCollection('Foo')->insert($array);

Depending on how you want to store your objects, you may want to use DBRefs instead of storing nested objects all at once, so you can easily find them separately afterwards. If not, just make your toArray method recursive.

like image 173
netcoder Avatar answered Oct 22 '25 05:10

netcoder