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
-
3can you show how your object look likeIbu– Ibu2011-06-19 21:03:31 +00:00Commented Jun 19, 2011 at 21:03
-
As what do you want your object to store? Do you want to access it's properties via mongo selectivly?hakre– hakre2011-06-19 21:08:42 +00:00Commented Jun 19, 2011 at 21:08
3 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.