Например, эти два документа находятся в одной коллекции. Поля name и foo являются обязательными.
Код: Выделить всё
{ 'name': 'scott', 'foo': 'abc123' }
{ 'name': 'jack' , 'foo': 'def456', 'bar': 'baz' }
На данный момент у меня есть класс Document, расширяющий следующий BaseDocument, и я создал собственный прослушиватель для события PostPersist, чтобы обновить постоянный документ с помощью пользовательского поля.
Код: Выделить всё
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);
}
}
Подробнее здесь: https://stackoverflow.com/questions/145 ... b-document
Мобильная версия