目前,从Mongo DB获取的每个文档都转到stdClass
对象。我想直接将它加载到我自己的自定义类中。
班级
class TestClass {
private $id;
private $class;
function __construct($id, $name) {
$this->id = $id;
$this->class = $class;
}
}
代码
$m = MongoDB\Driver\Manager('mongodb://<user>:<pass>@<host>/<db>');
$query = MongoDB\Driver\Query(['name' => 'TestFirst']);
// I tried adding the following line, but it says that the constructor args are missing.
// If I omit it, it just adds each cursor object as an instance of stdClass
$opt = ['cursor' => new TestClass];
$results = $m->executeQuery('newDb.testCollection', $query, $opt);
foreach ($results as $document) {
var_dump($document);
}
我想要实现的目标是什么,或者我是否需要浏览每个stdClass
对象并将其转换为TestClass
的实例?
答案 0 :(得分:1)
类本身需要实现MongoDB\BSON\Unserializable
接口和bsonUnserialize(array $data)
方法,以将数组从BSON数据转换为相关类。
class TestClass implements MongoDB\BSON\Unserializable, MongoDB\BSON\Serializable {
private $id;
private $name;
function __construct ($id, $name) {
$this->id = $id;
$this->name = $name;
}
function bsonUnserialize(array $data) {
// This will be called *instead* of the constructor if unserializing
$this->id = $data['_id'];
$this->id = $data['name'];
}
}
需要设置从查询返回的MongoDB\Driver\Cursor
的类型映射,以将文档映射到自定义类的实例。完成的代码看起来像这样。
$mongo = new MongoDB\Driver\Manager($constr);
$query = MongoDB\Driver\Query(['name' => 'TestFirst']);
$cursor = $mongo->executeQuery($query);
$cursor->setTypeMap('root' => 'array', 'document' => 'TestClass', 'array' => 'array');
foreach ($cursor as $doc) {
var_dump($doc);
}