MongoModel.class.php
14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Model;
use Think\Model;
/**
* MongoModel模型类
* 实现了ODM和ActiveRecords模式
*/
class MongoModel extends Model
{
// 主键类型
const TYPE_OBJECT = 1;
const TYPE_INT = 2;
const TYPE_STRING = 3;
// 主键名称
protected $pk = '_id';
// _id 类型 1 Object 采用MongoId对象 2 Int 整形 支持自动增长 3 String 字符串Hash
protected $_idType = self::TYPE_OBJECT;
// 主键是否自增
protected $_autoinc = true;
// Mongo默认关闭字段检测 可以动态追加字段
protected $autoCheckFields = false;
// 链操作方法列表
protected $methods = array(
'table',
'order',
'auto',
'filter',
'validate'
);
/**
* 利用__call方法实现一些特殊的Model方法
*
* @access public
* @param string $method
* 方法名称
* @param array $args
* 调用参数
* @return mixed
*/
public function __call($method, $args)
{
if (in_array(strtolower($method), $this->methods, true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
} elseif (strtolower(substr($method, 0, 5)) == 'getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method, 5));
$where[$field] = $args[0];
return $this->where($where)->find();
} elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
// 根据某个字段获取记录的某个值
$name = parse_name(substr($method, 10));
$where[$name] = $args[0];
return $this->where($where)->getField($args[1]);
} else {
E(__CLASS__ . ':' . $method . L('_METHOD_NOT_EXIST_'));
return;
}
}
/**
* 获取字段信息并缓存 主键和自增信息直接配置
*
* @access public
* @return void
*/
public function flush()
{
// 缓存不存在则查询数据表信息
$fields = $this->db->getFields();
if (! $fields) { // 暂时没有数据无法获取字段信息 下次查询
return false;
}
$this->fields = array_keys($fields);
foreach ($fields as $key => $val) {
// 记录字段类型
$type[$key] = $val['type'];
}
// 记录字段类型信息
if (C('DB_FIELDTYPE_CHECK')) {
$this->fields['_type'] = $type;
}
// 2008-3-7 增加缓存开关控制
if (C('DB_FIELDS_CACHE')) {
// 永久缓存数据表信息
$db = $this->dbName ? $this->dbName : C('DB_NAME');
F('_fields/' . $db . '.' . $this->name, $this->fields);
}
}
// 写入数据前的回调方法 包括新增和更新
protected function _before_write(&$data)
{
$pk = $this->getPk();
// 根据主键类型处理主键数据
if (isset($data[$pk]) && $this->_idType == self::TYPE_OBJECT) {
$data[$pk] = new \MongoId($data[$pk]);
}
}
/**
* count统计 配合where连贯操作
*
* @access public
* @return integer
*/
public function count()
{
// 分析表达式
$options = $this->_parseOptions();
return $this->db->count($options);
}
/**
* 获取唯一值
*
* @access public
* @return array | false
*/
public function distinct($field, $where = array())
{
// 分析表达式
$this->options = $this->_parseOptions();
$this->options['where'] = array_merge((array) $this->options['where'], $where);
$command = array(
"distinct" => $this->options['table'],
"key" => $field,
"query" => $this->options['where']
);
$result = $this->command($command);
return isset($result['values']) ? $result['values'] : false;
}
/**
* 获取下一ID 用于自动增长型
*
* @access public
* @param string $pk
* 字段名 默认为主键
* @return mixed
*/
public function getMongoNextId($pk = '')
{
if (empty($pk)) {
$pk = $this->getPk();
}
return $this->db->getMongoNextId($pk);
}
/**
* 新增数据
*
* @access public
* @param mixed $data
* 数据
* @param array $options
* 表达式
* @param boolean $replace
* 是否replace
* @return mixed
*/
public function add($data = '', $options = array(), $replace = false)
{
if (empty($data)) {
// 没有传递数据,获取当前数据对象的值
if (! empty($this->data)) {
$data = $this->data;
// 重置数据
$this->data = array();
} else {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
// 数据处理
$data = $this->_facade($data);
if (false === $this->_before_insert($data, $options)) {
return false;
}
// 写入数据到数据库
$result = $this->db->insert($data, $options, $replace);
if (false !== $result) {
$this->_after_insert($data, $options);
if (isset($data[$this->getPk()])) {
return $data[$this->getPk()];
}
}
return $result;
}
// 插入数据前的回调方法
protected function _before_insert(&$data, $options)
{
// 写入数据到数据库
if ($this->_autoinc && $this->_idType == self::TYPE_INT) { // 主键自动增长
$pk = $this->getPk();
if (! isset($data[$pk])) {
$data[$pk] = $this->db->getMongoNextId($pk);
}
}
}
public function clear()
{
return $this->db->clear();
}
// 查询成功后的回调方法
protected function _after_select(&$resultSet, $options)
{
array_walk($resultSet, array(
$this,
'checkMongoId'
));
}
/**
* 获取MongoId
*
* @access protected
* @param array $result
* 返回数据
* @return array
*/
protected function checkMongoId(&$result)
{
if (is_object($result['_id'])) {
$result['_id'] = $result['_id']->__toString();
}
return $result;
}
// 表达式过滤回调方法
protected function _options_filter(&$options)
{
$id = $this->getPk();
if (isset($options['where'][$id]) && is_scalar($options['where'][$id]) && $this->_idType == self::TYPE_OBJECT) {
$options['where'][$id] = new \MongoId($options['where'][$id]);
}
}
/**
* 查询数据
*
* @access public
* @param mixed $options
* 表达式参数
* @return mixed
*/
public function find($options = array())
{
if (is_numeric($options) || is_string($options)) {
$id = $this->getPk();
$where[$id] = $options;
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
$result = $this->db->find($options);
if (false === $result) {
return false;
}
if (empty($result)) { // 查询结果为空
return null;
} else {
$this->checkMongoId($result);
}
$this->data = $result;
$this->_after_find($this->data, $options);
return $this->data;
}
/**
* 字段值增长
*
* @access public
* @param string $field
* 字段名
* @param integer $step
* 增长值
* @return boolean
*/
public function setInc($field, $step = 1)
{
return $this->setField($field, array(
'inc',
$step
));
}
/**
* 字段值减少
*
* @access public
* @param string $field
* 字段名
* @param integer $step
* 减少值
* @return boolean
*/
public function setDec($field, $step = 1)
{
return $this->setField($field, array(
'inc',
'-' . $step
));
}
/**
* 获取一条记录的某个字段值
*
* @access public
* @param string $field
* 字段名
* @param string $spea
* 字段数据间隔符号
* @return mixed
*/
public function getField($field, $sepa = null)
{
$options['field'] = $field;
$options = $this->_parseOptions($options);
if (strpos($field, ',')) { // 多字段
if (is_numeric($sepa)) { // 限定数量
$options['limit'] = $sepa;
$sepa = null; // 重置为null 返回数组
}
$resultSet = $this->db->select($options);
if (! empty($resultSet)) {
$_field = explode(',', $field);
$field = array_keys($resultSet[0]);
$key = array_shift($field);
$key2 = array_shift($field);
$cols = array();
$count = count($_field);
foreach ($resultSet as $result) {
$name = $result[$key];
if (2 == $count) {
$cols[$name] = $result[$key2];
} else {
$cols[$name] = is_null($sepa) ? $result : implode($sepa, $result);
}
}
return $cols;
}
} else {
// 返回数据个数
if (true !== $sepa) { // 当sepa指定为true的时候 返回所有数据
$options['limit'] = is_numeric($sepa) ? $sepa : 1;
} // 查找符合的记录
$result = $this->db->select($options);
if (! empty($result)) {
if (1 == $options['limit']) {
return reset($result)[$field];
}
foreach ($result as $val) {
$array[] = $val[$field];
}
return $array;
}
}
return null;
}
/**
* 执行Mongo指令
*
* @access public
* @param array $command
* 指令
* @return mixed
*/
public function command($command, $options = array())
{
$options = $this->_parseOptions($options);
return $this->db->command($command, $options);
}
/**
* 执行MongoCode
*
* @access public
* @param string $code
* MongoCode
* @param array $args
* 参数
* @return mixed
*/
public function mongoCode($code, $args = array())
{
return $this->db->execute($code, $args);
}
// 数据库切换后回调方法
protected function _after_db()
{
// 切换Collection
$this->db->switchCollection($this->getTableName(), $this->dbName ? $this->dbName : C('db_name'));
}
/**
* 得到完整的数据表名 Mongo表名不带dbName
*
* @access public
* @return string
*/
public function getTableName()
{
if (empty($this->trueTableName)) {
$tableName = ! empty($this->tablePrefix) ? $this->tablePrefix : '';
if (! empty($this->tableName)) {
$tableName .= $this->tableName;
} else {
$tableName .= parse_name($this->name);
}
$this->trueTableName = strtolower($tableName);
}
return $this->trueTableName;
}
/**
* 分组查询
*
* @access public
* @return string
*/
public function group($key, $init, $reduce, $option = array())
{
$option = $this->_parseOptions($option);
// 合并查询条件
if (isset($option['where'])) {
$option['condition'] = array_merge((array) $option['condition'], $option['where']);
}
return $this->db->group($key, $init, $reduce, $option);
}
/**
* 返回Mongo运行错误信息
*
* @access public
* @return json
*/
public function getLastError()
{
return $this->db->command(array(
'getLastError' => 1
));
}
/**
* 返回指定集合的统计信息,包括数据大小、已分配的存储空间和索引的大小
*
* @access public
* @return json
*/
public function status()
{
$option = $this->_parseOptions();
return $this->db->command(array(
'collStats' => $option['table']
));
}
/**
* 取得当前数据库的对象
*
* @access public
* @return object
*/
public function getDB()
{
return $this->db->getDB();
}
/**
* 取得集合对象,可以进行创建索引等查询
*
* @access public
* @return object
*/
public function getCollection()
{
return $this->db->getCollection();
}
}