Doctrine MongoDB文档中的自定义字段

时间:2013-01-26 02:46:14

标签: symfony doctrine-orm doctrine-odm

我在项目中有一项特殊要求,要求使用MongoDB Collection,其中包含Documents不同的字段集。

例如,这两个Documents位于同一个集合中。 namefoo字段是必填字段。

{ 'name': 'scott', 'foo': 'abc123' }
{ 'name': 'jack' , 'foo': 'def456', 'bar': 'baz' }

使用Doctrine MongoDB ODM,Document类中将指定Document字段。

至于现在,我的Document类扩展了以下BaseDocument并为PostPersist事件创建了自定义侦听器,以使用自定义字段更新持久性Document

BaseDocument上课:

class BaseDocument
{
    protected $customFields;

    public function __construct()
    {
        $this->customFields = array();
    }

    public function setCustomField($name, $value)
    {
        if (\property_exists($this, $name)) {
            throw new \InvalidArgumentException("Object property '$name' exists, can't be assigned to a custom field");
        }
        $this->customFields[$name] = $value;
    }

    public function getCustomField($name)
    {
        if (\array_key_exists($name, $this->customFields)) {
            return $this->customFields[$name];
        }

        throw new \InvalidArgumentException("Custom field '$name' does not exists");
    }

    public function getCustomFields()
    {
        return $this->customFields;
    }
}

postPersist听众:

class CustomFieldListener
{
    public function postPersist(LifecycleEventArgs $args)
    {   
        $dm = $args->getDocumentManager();
        $document = $args->getDocument();

        $collection = $dm->getDocumentCollection(\get_class($document));
        $criteria = array('_id' => new \MongoID($document->getId()));
        $mongoDoc = $collection->findOne($criteria);
        $mongoDoc = \array_merge($mongoDoc, $document->getCustomFields());;
        $collection->update($criteria, $mongoDoc);
    } 
}

当前的解决方案根本不优雅,并且需要insertupdate次调用才能插入单个Document。在持久化,阅读和阅读时,将自定义字段注入Document的更好方法是什么?更新

0 个答案:

没有答案