3 +----------------------------------------------------------------------+
4 | Copyright (c) 2009 The PHP Group |
5 +----------------------------------------------------------------------+
6 | This source file is subject to version 3.0 of the PHP license, |
7 | that is bundled with this package in the file LICENSE, and is |
8 | available through the world-wide-web at the following url: |
9 | http://www.php.net/license/3_0.txt. |
10 | If you did not receive a copy of the PHP license and are unable to |
11 | obtain it through the world-wide-web, please send a note to |
12 | license@php.net so we can mail you a copy immediately. |
13 +----------------------------------------------------------------------+
14 | Authors: Cesar Rodas <crodas@php.net> |
15 +----------------------------------------------------------------------+
19 // Class FilterException {{{
23 * This is Exception is thrown if any validation
24 * fails when save() is called.
27 final class FilterException
extends Exception
32 // array get_object_vars_ex(stdobj $obj) {{{
34 * Simple hack to avoid get private and protected variables
40 function get_object_vars_ex($obj)
42 return get_object_vars($obj);
49 * Simple ActiveRecord pattern built on top of MongoDB. This class
50 * aims to provide easy iteration, data validation before update,
51 * and efficient update.
53 * @author César D. Rodas <crodas@php.net>
54 * @license PHP License
55 * @package ActiveMongo
59 abstract class ActiveMongo
implements Iterator
68 private static $_collections;
70 * Current connection to MongoDB
72 * @type MongoConnection
74 private static $_conn;
86 private static $_host;
92 private $_current = array();
98 private $_cursor = null;
100 * Current document ID
107 // string getCollectionName() {{{
109 * Get Collection Name, by default the class name,
110 * but you it can be override at the class itself to give
113 * @return string Colleciton Name
115 protected function getCollectionName()
117 return strtolower(get_class($this));
121 // void install() {{{
125 * This static method iterate over the classes lists,
126 * and execute the setup() method on every ActiveMongo
127 * subclass. You should do this just once.
130 final public static function install()
132 $classes = array_reverse(get_declared_classes());
133 foreach ($classes as $class)
135 if ($class == __CLASS__
) {
138 if (is_subclass_of($class, __CLASS__
)) {
146 // void connection($db, $host) {{{
150 * This method setup parameters to connect to a MongoDB
151 * database. The connection is done when it is needed.
153 * @param string $db Database name
154 * @param string $host Host to connect
158 final public static function connect($db, $host='localhost')
160 self
::$_host = $host;
165 // MongoConnection _getConnection() {{{
169 * Get a valid database connection
171 * @return MongoConnection
173 final protected static function _getConnection()
175 if (is_null(self
::$_conn)) {
176 self
::$_conn = new Mongo(self
::$_host);
178 return self
::$_conn->selectDB(self
::$_db);
182 // MongoCollection _getCollection() {{{
186 * Get a collection connection.
188 * @return MongoCollection
190 final protected function _getCollection()
192 $colName = $this->getCollectionName();
193 return self
::_getConnection()->selectCollection($colName);
197 // bool getCurrentSubDocument(array &$document, string $parent_key, array $values, array $past_values) {{{
199 * Generate Sub-document
201 * This method build the difference between the current sub-document,
202 * and the origin one. If there is no difference, it would do nothing,
203 * otherwise it would build a document containing the differences.
205 * @param array &$document Document target
206 * @param string $parent_key Parent key name
207 * @param array $values Current values
208 * @param array $past_values Original values
212 function getCurrentSubDocument(&$document, $parent_key, Array $values, Array $past_values)
215 * The current property is a embedded-document,
216 * now we're looking for differences with the
217 * previous value (because we're on an update).
219 * It behaves exactly as getCurrentDocument,
220 * but this is simples (it doesn't support
223 foreach ($values as $key => $value) {
224 $super_key = "{$parent_key}.{$key}";
225 if (is_array($value)) {
227 * Inner document detected
229 if (!isset($past_values[$key]) ||
!is_array($past_values[$key])) {
231 * We're lucky, it is a new sub-document,
234 $document['$set'][$super_key] = $value;
237 * This is a document like this, we need
238 * to find out the differences to avoid
241 if (!$this->getCurrentSubDocument($document, $super_key, $value, $past_values[$key])) {
247 if (!isset($past_values[$key]) ||
$past_values[$key] != $value) {
248 $document['$set'][$super_key] = $value;
252 foreach (array_diff(array_keys($past_values), array_keys($values)) as $key) {
253 $super_key = "{$parent_key}.{$key}";
254 $document['$unset'][$super_key] = 1;
261 // array getCurrentDocument(bool $update) {{{
263 * Get Current Document
265 * Based on this object properties a new document (Array)
266 * is returned. If we're modifying an document, just the modified
267 * properties are included in this document, which uses $set,
268 * $unset, $pushAll and $pullAll.
271 * @param bool $update
275 final protected function getCurrentDocument($update=false, $current=false)
278 $object = get_object_vars_ex($this);
281 $current = (array)$this->_current
;
284 foreach ($object as $key => $value) {
289 if (is_array($value) && isset($current[$key])) {
291 * If the Field to update is an array, it has a different
292 * behaviour other than $set and $unset. Fist, we need
293 * need to check if it is an array or document, because
294 * they can't be mixed.
297 if (!is_array($current[$key])) {
299 * We're lucky, the field wasn't
300 * an array previously.
302 $this->_call_filter($key, $value, $current[$key]);
303 $document['$set'][$key] = $value;
307 if (!$this->getCurrentSubDocument($document, $key, $value, $current[$key])) {
308 throw new Exception("{$key}: Array and documents are not compatible");
310 } else if(!isset($current[$key]) ||
$value !== $current[$key]) {
312 * It is 'linear' field that has changed, or
315 $past_value = isset($current[$key]) ?
$current[$key] : null;
316 $this->_call_filter($key, $value, $past_value);
317 $document['$set'][$key] = $value;
321 * It is a document insertation, so we
322 * create the document.
324 $this->_call_filter($key, $value, null);
325 $document[$key] = $value;
329 /* Updated behaves in a diff. way */
331 foreach (array_diff(array_keys($this->_current
), array_keys($object)) as $property) {
332 if ($property == '_id') {
335 $document['$unset'][$property] = 1;
339 if (count($document) == 0) {
346 // void _call_filter(string $key, mixed &$value, mixed $past_value) {{{
350 * This method check if the current document property has
351 * a filter method, if so, call it.
353 * If the filter returns false, throw an Exception.
357 private function _call_filter($key, &$value, $past_value)
359 $filter = array($this, "{$key}_filter");
360 if (is_callable($filter)) {
361 $filter = call_user_func_array($filter, array(&$value, $past_value));
362 if ($filter===false) {
363 throw new FilterException("{$key} filter failed");
365 $this->$key = $value;
370 // void setCursor(MongoCursor $obj) {{{
374 * This method receive a MongoCursor and make
377 * @param MongoCursor $obj
381 final protected function setCursor(MongoCursor
$obj)
383 $this->_cursor
= $obj;
384 $this->setResult($obj->getNext());
390 * Reset our Object, delete the current cursor if any, and reset
395 final function reset()
398 $this->_cursor
= null;
399 $this->setResult(array());
403 // void setResult(Array $obj) {{{
407 * This method takes an document and copy it
408 * as properties in this object.
414 final protected function setResult($obj)
416 /* Unsetting previous results, if any */
417 foreach (array_keys((array)$this->_current
) as $key) {
421 /* Add our current resultset as our object's property */
422 foreach ((array)$obj as $key => $value) {
423 $this->$key = $value;
426 /* Save our record */
427 $this->_current
= $obj;
431 // this find([$_id]) {{{
435 * Really simple find, which uses this object properties
438 * @return object this
440 function find(MongoID
$_id = null)
442 $vars = $this->getCurrentDocument();
446 $res = $this->_getCollection()->find($vars);
447 $this->setCursor($res);
452 // void save(bool $async) {{{
456 * This method save the current document in MongoDB. If
457 * we're modifying a document, a update is performed, otherwise
458 * the document is inserted.
460 * On updates, special operations such as $set, $pushAll, $pullAll
461 * and $unset in order to perform efficient updates
467 final function save($async=true)
469 $update = isset($this->_id
) && $this->_id
InstanceOf MongoID
;
470 $conn = $this->_getCollection();
471 $obj = $this->getCurrentDocument($update);
472 if (count($obj) == 0) {
473 return; /*nothing to do */
476 $this->pre_save($update ?
'update' : 'create', $obj);
478 $conn->update(array('_id' => $this->_id
), $obj);
479 foreach ($obj as $key => $value) {
480 $this->_current
[$key] = $value;
484 $conn->insert($obj, $async);
485 $this->_id
= $obj['_id'];
486 $this->_current
= $obj;
494 * Delete the current document
498 final function delete()
500 if ($this->valid()) {
501 return $this->_getCollection()->remove(array('_id' => $this->_id
));
509 * Delete the current colleciton and all its documents
513 final function drop()
515 $this->_getCollection()->drop();
516 $this->setResult(array());
517 $this->_cursor
= null;
523 * Return the number of documents in the actual request. If
524 * we're not in a request, it will return 0.
528 final function count()
530 if ($this->valid()) {
531 return $this->_cursor
->count();
541 * Return if we're on an iteration and if it is still valid
545 final function valid()
547 return $this->_cursor
InstanceOf MongoCursor
&& $this->_cursor
->valid();
553 * Move to the next document
557 final function next()
559 return $this->_cursor
->next();
563 // this current() {{{
565 * Return the current object, and load the current document
566 * as this object property
570 final function current()
572 $this->setResult($this->_cursor
->current());
579 * Go to the first document
581 final function rewind()
583 return $this->_cursor
->rewind();
589 * Return the current document ID. If there is
590 * no document it would return false.
592 * @return object|false
594 final public function getID()
596 if ($this->_id
instanceof MongoID
) {
605 * Return the current key
611 return $this->getID();
615 // void pre_save($action, & $document) {{{
619 * This method is fired just before an insert or updated. The document
620 * is passed by reference, so it can be modified. Also if for instance
621 * one property is missing an Exception could be thrown to avoid
625 * @param string $action Update or Create
626 * @param array &$document Document that will be sent to MongoDB.
630 protected function pre_save($action, Array &$document)
635 // void on_save() {{{
639 * This method is fired right after an insert is performed.
643 protected function on_save()
648 // void on_update() {{{
652 * This method is fired right after an update is performed.
656 protected function on_update()
661 // void on_iterate() {{{
665 * This method is fired right after a new document is loaded
666 * from the recorset, it could be useful to load references to other
671 protected function on_iterate()
678 * This method should contain all the indexes, and shard keys
679 * needed by the current collection. This try to make
680 * installation on development environments easier.
694 * vim600: sw=4 ts=4 fdm=marker