Exemple #1
0
 public function __construct(array $document = array(), $inner = false)
 {
     $properties_metadata = $this->detectPropertyMetadata();
     if ($inner) {
         $fields = $this->fields;
     } else {
         $fields = array_merge_recursive($this->defaultFields, $this->fields);
     }
     //        // 清楚无关数据
     //        foreach ($document as $key => $value) {
     //            if (!isset($fields[$key])) {
     //                unset($document[$key]);
     //            }
     //        }
     // 添加默认值
     foreach ($fields as $key => $default) {
         if (!isset($document[$key])) {
             $document[$key] = $default;
         }
     }
     // 构造
     foreach ($document as $key => $value) {
         if (is_array($value)) {
             // 将下划线替换成驼峰
             $property_key = lcfirst($this->camelize($key));
             if (isset($properties_metadata[$property_key])) {
                 $class_flag = $properties_metadata[$property_key];
                 if (strpos($class_flag, '[]') !== false) {
                     $doc = new MongoDocument(array(), true);
                     foreach ($value as $k => $v) {
                         if (is_array($v)) {
                             $class_flag = str_replace('[]', '', $class_flag);
                             $doc->set($k, new $class_flag($v));
                         } else {
                             $doc[$k] = $v;
                         }
                     }
                     $document[$key] = $doc;
                 } else {
                     $document[$key] = new $class_flag($value);
                 }
             }
         }
     }
     $this->data = $document;
 }
Exemple #2
0
 /**
  * 保存文档
  * @param MongoDocument $document
  */
 public function saveDocument(MongoDocument $document)
 {
     $document->setUpdateTimestamp(time());
     $doc = $document->toArray();
     try {
         $doc_id = $doc['_id'];
         unset($doc['_id']);
         $this->getMongoCollection(true)->findAndModify(array('_id' => $doc_id), array('$set' => $doc), null, array('new' => true, 'upsert' => true));
     } catch (\Exception $e) {
         throw new $e();
     }
 }