-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathDbo.php
475 lines (435 loc) · 13.9 KB
/
Dbo.php
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
<?php
/**
* Class Dbo
*
* @package SimpleMongoPhp
* @author Ian White ([email protected])
* @version 1.2
*
* This is a simple library to allow you to work with simple data objects.
*
* To set up, all you need to do is:
* - include() or require() the Db.php file, and this file
* - call Db::addConnection()
* - create any number of data object classes that extend Dbo
* - call Dbo::addClass(<class name>, <collection name>) for each class
*
* Example usage (this code does basically the same thing as the sample code in Db.php)
* $mongo = new Mongo();
* define('MONGODB_NAME', 'lost');
* class LostPerson extends Dbo {
* function rollCall() {
* echo "$this->name is a " . ($this->goodguy ? 'good' : 'bad') . " guy!\n";
* }
* }
* Dbo::addClass('LostPerson', 'people');
*
* Db::drop('people');
* Db::batchInsert('people', array(
* array('name' => 'Jack', 'sex' => 'M', 'goodguy' => true),
* array('name' => 'Kate', 'sex' => 'F', 'goodguy' => true),
* array('name' => 'Locke', 'sex' => 'M', 'goodguy' => true),
* array('name' => 'Hurley', 'sex' => 'M', 'goodguy' => true),
* array('name' => 'Ben', 'sex' => 'M', 'goodguy' => false),
* ));
* foreach (Dbo::find('LostPerson', array('goodguy' => true), array('sort' => array('name' => 1))) as $p) {
* $p->rollCall();
* }
* $ben = Dbo::findOne('LostPerson', array('name' => 'Ben'));
* $locke = Dbo::findOne('LostPerson', array('name' => 'Locke'));
* $ben->enemy = Dbo::toRef($locke);
* $ben->goodguy = null;
* Dbo::save($ben);
*
* This library may be freely distributed and modified for any purpose.
**/
class Dbo {
public $_data = array();
/**
* Constructor optionally takes the field values to prepopulate the object with
*
* @param array $data
**/
function __construct($data = array()) {
$this->_data = $data;
}
/**
* Attribute accessor overload returns a field property, or null if it doesn't exist.
*
* The "id" field behaves specially and returns the string representation of the MongoId.
* This is convenient in a number of situations, especially comparisons:
* ($obj1->_id == $obj2->_id) is not a valid test but ($obj1->id == $obj2->id) is
*
* @param string $field
* @return mixed
**/
function __get($field) {
if ($field == 'id') {
return "$this->_id";
}
$i = strpos($field, '.');
if ($i !== false) {
return $this->_getDotNotation($field, $this->_data);
}
return isset($this->_data[$field]) ? $this->_data[$field] : null;
}
/**
* Attribute setter overload, set a field property.
*
* @param string $field
* @param mixed $value
* @return mixed
**/
function __set($field, $value) {
$i = strpos($field, '.');
if ($i !== false) {
$this->_setDotNotation($field, $value, $this->_data);
} else {
return $this->_data[$field] = $value;
}
}
/**
* isset() overload, checks if a field value is set
*
* @param string $field
* @return boolean
**/
function __isset($field) {
return isset($this->_data[$field]);
}
/**
* unset() overload, unsets a field vlaue
*
* @param string $field
* @return boolean
**/
function __unset($field) {
unset($this->_data[$field]);
}
/**
* Returns all attributes as array
*
* @return array
*/
function getAttributes() {
return $this->_data;
}
/**
* This function will be called immediately prior to saving an object.
*
* Override in subclasses to, for example, set a created_time timestamp, or update dependent
* fields, or validate the data, or whatever you like.
*
*/
function presave() {
}
function preremove() {
}
/**
* Reload this object's data from db
*
* @return void
*/
public function reload()
{
if (isset($this->_id)) {
$class = get_class($this);
$collection = self::getCollection($class);
$this->_data = Db::findOne($collection, $this->_id);
}
}
// Guts
private function _getDotNotation($fields, &$current) {
$i = strpos($fields, '.');
if ($i !== false) {
$field = substr($fields, 0, $i);
if (!isset($current[$field])) {
return null;
}
$current =& $current[$field];
return $this->_getDotNotation(substr($fields, $i+1), $current);
} else {
return isset($current[$fields]) ? $current[$fields] : null;
}
}
private function _setDotNotation($fields, $value, &$current) {
$i = strpos($fields, '.');
if ($i !== false) {
$field = substr($fields, 0, $i);
if (!isset($current[$field])) {
$current[$field] = array();
}
$current =& $current[$field];
return $this->_setDotNotation(substr($fields, $i+1), $value, $current);
} else {
$current[$fields] = $value;
}
}
// Static functions
/**
* Register that a class belongs with a collection.
*
* If the first parameter is a associative array, you can register many classes at once.
*
* @param mixed $class
* @param string $collection
**/
static function addClass($class, $collection = null) {
if (is_array($class)) {
foreach ($class as $k => $v) {
self::addClass($k, $v);
}
} else {
if (!isset($GLOBALS['MONGODB_CLASSES'])) {
$GLOBALS['MONGODB_CLASSES'] = array();
}
$GLOBALS['MONGODB_CLASSES'][$collection] = $class;
if (!isset($GLOBALS['MONGODB_COLLECTIONS'])) {
$GLOBALS['MONGODB_COLLECTIONS'] = array();
}
$GLOBALS['MONGODB_COLLECTIONS'][$class] = $collection;
}
}
/**
* Returns the name of the class that is associated with a collection.
*
* @param string $collection
* @return string
**/
static function getClass($collection) {
if (!isset($GLOBALS['MONGODB_CLASSES'][$collection])) {
throw new Exception("Dbo::getClass cannot find $collection class");
}
return $GLOBALS['MONGODB_CLASSES'][$collection];
}
/**
* Returns the name of a collection that is associated with a class.
*
* @param string $class
* @return string
**/
static function getCollection($class) {
if (!isset($GLOBALS['MONGODB_COLLECTIONS'][$class])) {
throw new Exception("Dbo::getCollection cannot find $class collection");
}
return $GLOBALS['MONGODB_COLLECTIONS'][$class];
}
/**
* Returns an iterator that will iterate through objects -- this should allow you to
* go through large datasets without excessive memory allocation.
*
* @param string $class
* @param array $query
* @param array $options
* @return Dboiterator
**/
static function find($class, $query = array(), $options = array()) {
$collection = self::getCollection($class);
$result = Db::find($collection, $query, $options);
return new Dboiterator($class, $result);
}
/**
* Just like Db::finda() but will return an array of objects
*
* @param string $class
* @param array $query
* @param array $options
* @return array
**/
static function finda($class, $query = array(), $options = array()) {
$collection = self::getCollection($class);
$result = Db::find($collection, $query, $options);
$objects = array();
foreach ($result as $data) {
$objects[] = new $class($data);
}
return $objects;
}
/**
* Find a single data object, or null if not found
*
* @param string $class
* @param mixed $id
* @return Dbo
**/
static function findOne($class, $id = array()) {
$collection = self::getCollection($class);
$data = Db::findOne($collection, $id);
return $data ? new $class($data) : null;
}
/**
* Count the number of objects matching a query in a collection (or all objects)
*
* @param string $collection
* @param array $query
* @return integer
**/
static function count($class, $query = array()) {
global $mongo;
$collection = self::getCollection($class);
$count = Db::count($collection, $query);
return $count ? $count : 0;
}
/**
* Saves a data object in the correct collection, calling presave() first
*
* @param Dbo $object
* @return boolean
**/
static function save($object) {
$class = get_class($object);
$collection = self::getCollection($class);
$object->presave();
return Db::save($collection, $object->_data);
}
/**
* Removes a data object from its collection
*
* @param Dbo $object
* @return boolean
**/
static function remove($object) {
$class = get_class($object);
$collection = self::getCollection($class);
$object->preremove();
return Db::remove($collection, array('_id' => $object->_id));
}
/**
* Looks up a database reference and returns a data object of the correct class
*
* @param array $dbref
* @return Dbo
**/
static function getRef($dbref) {
$class = self::getClass($dbref['$ref']);
$data = Db::getRef($dbref);
return $data ? new $class($data) : null;
}
/**
* Looks up references to the same collection in one query and returns data objects
* of the correct class
*
* @param string $collection
* @param array $ids
* @return array
*/
static function getRefs($collection, array $ids) {
$class = self::getClass($collection);
$data = Db::find($collection, array(
'_id' => array('$in' => $ids)
));
$objects = array();
foreach ($data as $id => $record) {
$objects[ array_search($id, $ids) ] = new $class($record);
}
ksort($objects);
return $objects;
}
/**
* Recursively looks up the database references in e.g. an array of database references,
* returning all references as data objects
*
* @param mixed $value
* @param boolean $keep_nulls
* @return mixed
**/
static function expandRefs($value, $keep_nulls = false) {
if (Db::isRef($value)) {
return self::getRef($value);
}
elseif (is_array($value)) {
// TODO: Temporay fix, remove this later
if (empty($value) || ($value[0] instanceof Dbo))
return $value;
// Check if all referenced objects are of the same type
$reference_map = array();
foreach ($value as $reference) {
$ref_collection = $reference['$ref'];
isset($reference_map[$ref_collection]) ||
$reference_map[$ref_collection] = array();
$ref_id = $reference['$id'];
$reference_map[$ref_collection][] = $ref_id;
}
$referenced_collections = array_keys($reference_map);
if (count($referenced_collections) == 1) {
$referenced_collection = $referenced_collections[0];
$referenced_ids = $reference_map[$referenced_collection];
$entries = self::getRefs($referenced_collection, $referenced_ids);
}
else {
$entries = array();
foreach ($reference_map as $collection => $ids) {
$entries = array_merge($entries, self::getRefs($collection, $ids));
}
}
return $keep_nulls ? $entries : array_filter($entries);
}
// Empty array or null
elseif (!$value) {
return $value;
}
throw new Exception("Don't know how to expand: " . gettype($value));
}
/**
* Converts an object or other data structure recursively to database references.
*
* @param mixed $value
* @return mixed
**/
static function toRef($value) {
if ($value instanceof Dbo) {
$class = get_class($value);
$collection = self::getCollection($class);
return array('$ref' => $collection, '$id' => $value->_id);
} else if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = self::toRef($v);
}
}
return $value;
}
}
/**
* Helper iterator class for Dbo::find(), implements the Iterator interface so you can
* foreach your way through the returned result and not worry about the details.
**/
class Dboiterator implements Iterator, Countable {
private $class;
private $resultset;
function __construct($class, $resultset) {
$this->class = $class;
$this->resultset = $resultset;
}
function current() {
$result = $this->resultset->current();
$obj = new $this->class($result);
$obj->_data = $result;
return $obj;
}
function key() {
return $this->resultset->key();
}
function next() {
return $this->resultset->next();
}
function rewind() {
return $this->resultset->rewind();
}
function valid() {
return $this->resultset->valid();
}
function count() {
return $this->resultset->count();
}
function skip($num) {
return $this->resultset->skip($num);
}
function toArray() {
$models = array();
foreach ($this as $id => $model) {
$models[$id] = $model;
}
reset($this);
return $models;
}
}