Mongodb中映射的动态实体定义

时间:2015-03-21 22:48:48

标签: php mongodb symfony

修改:还在处理我的问题。我最终使用@MongoDB \ EmbedDocument来保存复杂的Document,它似乎正在按预期工作。可悲的是,检索部分工作得不好。如果我检索一个非常基本的元素,它会很顺利。但是,就我使用EmbedDocument而言,我正在检索似乎是通过递归创建的额外数据和方法,并且不会停止。

有什么想法吗?


我目前在使用MongoDB和Symfony2时遇到了设计问题。我的目标是创建一个多态类,它允许我注册一个Document,其属性可以从Document更改为另一个。

我们的想法是使用MongoDB的无架构方法来保存可以即时定义的对象定义。

所以,我创建了一个抽象类来定义我的属性Type。我将从AbstractEntity扩展我的所有属性,并获得一些格式化的基本属性(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的精神)。

我愿意接受任何建议或讨论:) 谢谢:))

1 个答案:

答案 0 :(得分:0)

我终于使用EmbededDocument和EmbedMany注释成功保存了我的文档。由于递归循环,我仍然在获取结果方面存在问题,但我会在另一篇文章中解决这个问题。