Inserting a PHP Object Into a MONGO DB
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 objec开发者_开发百科ts as well. Thanks
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.
encode to JSON and insert to MongoDB.
If you want save your value into Mongo Object ID:
$param = 'ojkhalskdjfhs9df87as08df';
$this->insert($collection, [
'aaaaa' => new MongoId($param)
]);
精彩评论