将PHP对象插入MONGO DB [英] Inserting a PHP Object Into a MONGO DB
问题描述
我有一个要存储在Mongo数据库中的php对象.在数据库中存储对象的最佳方法是什么?我当时正在考虑遍历对象并创建一个数组,但这是一个复杂的对象,它也具有子对象.谢谢
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
推荐答案
最简单的方法可能是使对象可广播"到数组.
The easiest way is probably to make your object "castable" to an array.
如果要存储的属性是public
,则可以执行以下操作:
If the properties you want to store are public
, you can just do:
$array = (array)$foo;
否则,toArray
方法或使其实现Iterator
接口将起作用:
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,
));
}
}
很明显,您也可以使用get_object_vars
,Reflection等代替在getIterator
方法中对属性列表进行硬编码.
Obviously, you can also use get_object_vars
, Reflection and such instead of hardcoding the property list in the getIterator
method.
然后,只是:
$foo = new Foo;
$array = iterator_to_array($foo);
$mongodb->selectCollection('Foo')->insert($array);
根据要存储对象的方式,您可能希望使用DBRef而不是一次存储所有嵌套对象,因此以后可以轻松地分别find
将它们分开.如果不是,则使您的toArray
方法递归.
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.
这篇关于将PHP对象插入MONGO DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!