编辑:仍在处理我的问题。我最后使用了@MongoDB ''EmbeddDocument来保存复杂的文档,它似乎像预期的那样工作。遗憾的是,检索部分工作不太好。如果我检索到一个非常基本的元素,它运行得非常好。但就我使用EmbeddDocument而言,我正在检索额外的数据和方法,这些数据和方法似乎是通过递归创建的,并且不会停止。
知道吗?
我目前在将MongoDB与Symfony2一起使用时遇到了一个设计问题。我的目标是创建一个多态类,允许我注册一个具有可以从一个文档更改为另一个文档的属性的文档。
这个想法是使用MongoDB的无模式方法来保存可以动态定义的对象定义。
因此,我创建了一个抽象类来定义我的属性Type。我将从抽象实体扩展我的所有属性,并获得一些格式化的基本属性(String、Int…)
/**
* @MongoDB'MappedSuperclass
*/
abstract class AbstractEntity {
/**
* @MongoDB'Id
*/
protected $id;
/**
* @MongoDB'String
*/
protected $name;
/**
* @MongoDB'String
*/
protected $type;
/**
* Every basic element has an ID
* @return @MongoDB'Id
*/
public function getId() {
return $this->id;
}
// Here are methods, getters and setters
// ...
}
然后,我创建了一个类Document,它可以用我前面描述的一些基本属性进行扩展。My Document类包含一组属性。
/**
* @MongoDB'Document
*/
class Document extends AbstractEntity{
/**
* @MongoDB'???
*/
private $attributes = array();
public function __construct($name) {
$this->setType(TYPE::DOCUMENT);
$this->setName($name);
}
public function addAttribute($type, $name, $options = array()) {
$attribute = $this->attributeFactory($type, $name, $options);
array_push($this->attributes, $attribute);
return $this;
}
private function attributeFactory($type, $name, $options = array()) {
$entity = NULL;
if( $type == TYPE::STRING) {
$entity = new String($name);
}
return $entity;
}
}
通过这项工作,我希望能够在我的数据库中保存一个条目(一个文档),它可以描述一个新文档及其属性,比如:
{
"name" : "Character",
"type" : "Document",
"properties" : [
{
"name": "alias",
"type": "String"
},
// ...
]
}
遗憾的是,我是mongodb+symfony的新手,因为映射,我觉得自己被卡住了,这很好,但在无模式的方法中是有限的。
有人知道我如何才能做到这一点吗?或者我是否走错了方向?
在我的想法中,我想限制将我的文档定义拆分为从一个文档到多行的关系方法(而不是mongodb的精神)。
我愿意接受任何建议或讨论:)感谢:)
我终于成功地使用EmbeddedDocument和EmbeddMany注释保存了我的文档。由于递归循环,我在获得结果时仍然有问题,但我将在另一篇文章中解决这个问题。