3 +---------------------------------------------------------------------------------+
4 | Copyright (c) 2010 ActiveMongo |
5 +---------------------------------------------------------------------------------+
6 | Redistribution and use in source and binary forms, with or without |
7 | modification, are permitted provided that the following conditions are met: |
8 | 1. Redistributions of source code must retain the above copyright |
9 | notice, this list of conditions and the following disclaimer. |
11 | 2. Redistributions in binary form must reproduce the above copyright |
12 | notice, this list of conditions and the following disclaimer in the |
13 | documentation and/or other materials provided with the distribution. |
15 | 3. All advertising materials mentioning features or use of this software |
16 | must display the following acknowledgement: |
17 | This product includes software developed by César D. Rodas. |
19 | 4. Neither the name of the César D. Rodas nor the |
20 | names of its contributors may be used to endorse or promote products |
21 | derived from this software without specific prior written permission. |
23 | THIS SOFTWARE IS PROVIDED BY CÉSAR D. RODAS ''AS IS'' AND ANY |
24 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
25 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
26 | DISCLAIMED. IN NO EVENT SHALL CÉSAR D. RODAS BE LIABLE FOR ANY |
27 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
28 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
29 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
30 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
31 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
32 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE |
33 +---------------------------------------------------------------------------------+
34 | Authors: César Rodas <crodas@php.net> |
35 +---------------------------------------------------------------------------------+
38 // array get_document_vars(stdobj $obj) {{{
40 * Simple hack to avoid get private and protected variables
43 * @param bool $include_id
47 function get_document_vars($obj, $include_id=TRUE)
49 $document = get_object_vars($obj);
50 if ($include_id && $obj->getID()) {
51 $document['_id'] = $obj->getID();
57 if (version_compare(PHP_VERSION
, '5.3') < 0) {
58 require dirname(__FILE__
)."/Objects_compat.php";
60 require dirname(__FILE__
)."/Objects.php";
66 * Simple ActiveRecord pattern built on top of MongoDB. This class
67 * aims to provide easy iteration, data validation before update,
68 * and efficient update.
70 * @author César D. Rodas <crodas@php.net>
71 * @license BSD License
72 * @package ActiveMongo
76 abstract class ActiveMongo
implements Iterator
, Countable
, ArrayAccess
80 const FIND_AND_MODIFY
= 0x001;
85 * Current databases objects
95 private static $_namespace = NULL;
97 * Specific namespaces for each class
101 private static $_namespaces = array();
103 * Current collections objects
107 private static $_collections;
109 * Current connection to MongoDB
111 * @type MongoConnection
113 private static $_conn;
121 * List of events handlers
125 static private $_events = array();
127 * List of global events handlers
131 static private $_super_events = array();
137 private static $_host;
143 private static $_user;
150 private static $_pwd;
157 private $_current = array();
163 private $_cursor = NULL;
165 * Extended result cursor, used for FindAndModify now
169 private $_cursor_ex = NULL;
170 private $_cursor_ex_value;
172 * Count the findandmodify result counts
176 private $_findandmodify_cnt = 0;
177 /* value to modify */
178 private $_findandmodify;
180 /* {{{ Silly but useful query abstraction */
181 private $_cached = FALSE;
182 private $_query = NULL;
183 private $_sort = NULL;
186 private $_properties = NULL;
190 * Current document ID
197 * Tell if the current object
202 private $_cloned = FALSE;
205 final static function isAbstractChildClass($class)
207 $r = new ReflectionClass($class);
208 if ($r->IsAbstract())
210 // make sure it's a child
211 if ($r->isSubclassOf(__CLASS__
))
219 // GET CONNECTION CONFIG {{{
221 // setNameSpace($namespace='') {{{
223 * Set a namespace for all connections is it is called
224 * statically from ActiveMongo or for specific classes
225 * if it is called from an instance.
227 * @param string $namespace
231 final static function setNamespace($namespace='')
233 if (preg_match("#^[\-\_a-z0-9]*$#i", $namespace)) {
234 /* sort of standard late binding */
236 $context = get_class($this);
238 $context = get_called_class();
241 if ($context == __CLASS__ || self
::isAbstractChildClass($context)) {
242 self
::$_namespace = $namespace;
244 self
::$_namespaces[$context] = $namespace;
252 // collectionName() {{{
256 * Return the collection name (along with its namespace) for
257 * the current object.
259 * Warning: This must not be called statically from outside the
264 final public function collectionName()
267 /* Need to check if $this is instance of $parent
268 * because PHP5.2 fails detecting $this when a non-static
269 * method is called statically from another class ($this is
272 if (isset($this) && $this InstanceOf $parent) {
273 $collection = $this->getCollectionName();
274 $context = get_class($this);
276 /* ugly, it might fail if getCollectionName has some refernce to $this */
277 $context = get_called_class();
278 $collection = call_user_func(array($context, 'getCollectionName'));
281 if (isset(self
::$_namespaces[$context]) && self
::$_namespaces[$context]) {
282 $collection = self
::$_namespaces[$context].".{$collection}";
283 } else if (self
::$_namespace) {
284 $collection = self
::$_namespace.".{$collection}";
291 // string getCollectionName() {{{
293 * Get Collection Name, by default the class name,
294 * but you it can be override at the class itself to give
297 * @return string Collection Name
299 protected function getCollectionName()
302 return strtolower(get_class($this));
304 return strtolower(get_called_class());
309 // string getDatabaseName() {{{
311 * Get Database Name, by default it is used
312 * the db name set by ActiveMong::connect()
314 * @return string DB Name
316 protected function getDatabaseName()
318 if (is_NULL(self
::$_db)) {
319 throw new ActiveMongo_Exception("There is no information about the default DB name");
325 // void install() {{{
329 * This static method iterate over the classes lists,
330 * and execute the setup() method on every ActiveMongo
331 * subclass. You should do this just once.
334 final public static function install()
336 $classes = array_reverse(get_declared_classes());
337 foreach ($classes as $class)
339 $r = new ReflectionClass($class);
340 if ($r->IsAbstract()) // skip abstract ones
345 if ($class == __CLASS__
) {
348 if (is_subclass_of($class, __CLASS__
)) {
356 // void connection($db, $host) {{{
360 * This method setup parameters to connect to a MongoDB
361 * database. The connection is done when it is needed.
363 * @param string $db Database name
364 * @param string $host Host to connect
365 * @param string $user User (Auth)
366 * @param string $pwd Password (Auth)
370 final public static function connect($db, $host='localhost', $user = NULL, $pwd=NULL)
372 self
::$_host = $host;
374 self
::$_user = $user;
381 * Return TRUE is there is any active connection
386 final public static function isConnected()
388 return !is_null(self
::$_conn) ||
count(self
::$_dbs) > 0 ||
count(self
::$_collections) > 0;
394 * Destroy all connections objects to MongoDB if any.
398 final public static function disconnect()
401 self
::$_dbs = array();
402 self
::$_collections = array();
406 // MongoConnection _getConnection() {{{
410 * Get a valid database connection
412 * @return MongoConnection
414 final protected function _getConnection()
416 if (is_NULL(self
::$_conn)) {
417 if (is_NULL(self
::$_host)) {
418 self
::$_host = 'localhost';
420 self
::$_conn = new Mongo(self
::$_host);
423 $dbname = $this->getDatabaseName();
425 $dbname = self
::getDatabaseName();
427 if (!isSet(self
::$_dbs[$dbname])) {
428 self
::$_dbs[$dbname] = self
::$_conn->selectDB($dbname);
430 if ( !is_NULL(self
::$_user ) && !is_NULL(self
::$_pwd ) ) {
431 self
::$_dbs[$dbname]->authenticate(self
::$_user,self
::$_pwd);
435 return self
::$_dbs[$dbname];
439 // MongoCollection _getCollection() {{{
443 * Get a collection connection.
445 * @return MongoCollection
447 final protected function _getCollection()
450 $colName = $this->CollectionName();
452 $colName = self
::CollectionName();
454 if (!isset(self
::$_collections[$colName])) {
455 self
::$_collections[$colName] = self
::_getConnection()->selectCollection($colName);
457 return self
::$_collections[$colName];
463 // GET DOCUMENT TO SAVE OR UPDATE {{{
465 // getDocumentVars() {{{
472 final protected function getDocumentVars()
474 $variables = array();
475 foreach ((array)$this->__sleep() as $var) {
476 if (!property_exists($this, $var)) {
479 $variables[$var] = $this->$var;
485 // bool getCurrentSubDocument(array &$document, string $parent_key, array $values, array $past_values) {{{
487 * Generate Sub-document
489 * This method build the difference between the current sub-document,
490 * and the origin one. If there is no difference, it would do nothing,
491 * otherwise it would build a document containing the differences.
493 * @param array &$document Document target
494 * @param string $parent_key Parent key name
495 * @param array $values Current values
496 * @param array $past_values Original values
500 final function getCurrentSubDocument(&$document, $parent_key, Array $values, Array $past_values)
503 * The current property is a embedded-document,
504 * now we're looking for differences with the
505 * previous value (because we're on an update).
507 * It behaves exactly as getCurrentDocument,
508 * but this is simples (it doesn't support
511 foreach ($values as $key => $value) {
512 $super_key = "{$parent_key}.{$key}";
513 if (is_array($value)) {
515 * Inner document detected
517 if (!array_key_exists($key, $past_values) ||
!is_array($past_values[$key])) {
519 * We're lucky, it is a new sub-document,
522 $document['$set'][$super_key] = $value;
525 * This is a document like this, we need
526 * to find out the differences to avoid
529 if (!$this->getCurrentSubDocument($document, $super_key, $value, $past_values[$key])) {
534 } else if (!array_key_exists($key, $past_values) ||
$past_values[$key] !== $value) {
535 $document['$set'][$super_key] = $value;
539 foreach (array_diff(array_keys($past_values), array_keys($values)) as $key) {
540 $super_key = "{$parent_key}.{$key}";
541 $document['$unset'][$super_key] = 1;
548 // array getCurrentDocument(bool $update) {{{
550 * Get Current Document
552 * Based on this object properties a new document (Array)
553 * is returned. If we're modifying an document, just the modified
554 * properties are included in this document, which uses $set,
555 * $unset, $pushAll and $pullAll.
558 * @param bool $update
562 final protected function getCurrentDocument($update=FALSE, $current=FALSE)
565 $object = $this->getDocumentVars();
568 $current = (array)$this->_current
;
572 $this->findReferences($object);
574 $this->triggerEvent('before_validate', array(&$object, $current));
575 $this->triggerEvent('before_validate_'.($update?
'update':'creation'), array(&$object, $current));
577 foreach ($object as $key => $value) {
579 if (is_array($value) && isset($current[$key])) {
581 * If the Field to update is an array, it has a different
582 * behaviour other than $set and $unset. Fist, we need
583 * need to check if it is an array or document, because
584 * they can't be mixed.
587 if (!is_array($current[$key])) {
589 * We're lucky, the field wasn't
590 * an array previously.
592 $this->runFilter($key, $value, $current[$key]);
593 $document['$set'][$key] = $value;
597 if (!$this->getCurrentSubDocument($document, $key, $value, $current[$key])) {
598 throw new Exception("{$key}: Array and documents are not compatible");
600 } else if(!array_key_exists($key, $current) ||
$value !== $current[$key]) {
602 * It is 'linear' field that has changed, or
605 $past_value = isset($current[$key]) ?
$current[$key] : NULL;
606 $this->runFilter($key, $value, $past_value);
607 $document['$set'][$key] = $value;
611 * It is a document insertation, so we
612 * create the document.
614 $this->runFilter($key, $value, NULL);
615 $document[$key] = $value;
619 /* Updated behaves in a diff. way */
621 foreach (array_diff(array_keys($this->_current
), array_keys($object)) as $property) {
622 if ($property == '_id') {
625 $document['$unset'][$property] = 1;
629 if (count($document) == 0) {
633 $this->triggerEvent('after_validate', array(&$document));
634 $this->triggerEvent('after_validate_'.($update?
'update':'creation'), array(&$object));
642 // EVENT HANDLERS {{{
644 // addEvent($action, $callback) {{{
649 final static function addEvent($action, $callback)
651 if (!is_callable($callback)) {
652 throw new ActiveMongo_Exception("Invalid callback");
655 $class = get_called_class();
656 if ($class == __CLASS__ || self
::isAbstractChildClass($class)) {
657 $events = & self
::$_super_events;
659 $events = & self
::$_events[$class];
661 if (!isset($events[$action])) {
662 $events[$action] = array();
664 $events[$action][] = $callback;
669 // triggerEvent(string $event, Array $events_params) {{{
670 final function triggerEvent($event, Array $events_params = array(), $context=NULL)
674 $class = get_called_class();
677 $class = get_class($this);
684 $events = & self
::$_events[$class][$event];
685 $sevents = & self
::$_super_events[$event];
687 /* Super-Events handler receives the ActiveMongo class name as first param */
688 $sevents_params = array_merge(array($class), $events_params);
690 foreach (array('events', 'sevents') as $event_type) {
691 if (count($
$event_type) > 0) {
692 $params = "{$event_type}_params";
693 foreach ($
$event_type as $fnc) {
694 if (call_user_func_array($fnc, $
$params) === FALSE) {
702 case 'before_create':
703 case 'before_update':
704 case 'before_validate':
705 case 'before_delete':
710 case 'after_validate':
714 $fnc = array($obj, $event);
715 $params = "events_params";
716 if (is_callable($fnc)) {
717 call_user_func_array($fnc, $
$params);
724 // void runFilter(string $key, mixed &$value, mixed $past_value) {{{
728 * This method check if the current document property has
729 * a filter method, if so, call it.
731 * If the filter returns FALSE, throw an Exception.
735 protected function runFilter($key, &$value, $past_value)
737 $filter = array($this, "{$key}_filter");
738 if (is_callable($filter)) {
739 $filter = call_user_func_array($filter, array(&$value, $past_value));
740 if ($filter===FALSE) {
741 throw new ActiveMongo_FilterException("{$key} filter failed");
743 $this->$key = $value;
750 // void setCursor(MongoCursor $obj) {{{
754 * This method receive a MongoCursor and make
757 * @param MongoCursor $obj
761 final protected function setCursor(MongoCursor
$obj)
763 $this->_cursor
= $obj;
765 $this->setResult($obj->getNext());
769 // void setResult(Array $obj) {{{
773 * This method takes an document and copy it
774 * as properties in this object.
780 final protected function setResult($obj)
782 /* Unsetting previous results, if any */
783 foreach (array_keys(get_document_vars($this, FALSE)) as $key) {
788 /* Add our current resultset as our object's property */
789 foreach ((array)$obj as $key => $value) {
790 if ($key[0] == '$') {
793 $this->$key = $value;
796 /* Save our record */
797 $this->_current
= $obj;
801 // this find([$_id], [$fields], [$use_document_vars]) {{{
803 * find supports 4 modes of operation.
807 * Will search using the current document values assigned to this object
810 * $_id = a non-array value
811 * Will search for a document with matching ID
814 * $_id = a simple list (non-associative)
815 * Will search for all document with matching IDs
818 * $_id = an associative array
819 * Will use the array as the template
821 * $fields can be used to limit the return value to only certain fields
823 * By default, the document values are used for the search only in
824 * mode 1, but this can be changed by setting $use_document_vars to
825 * something other than null
827 * Really simple find, which uses this object properties
830 * @return object this
832 final function find($_id = NULL, $fields = null, $use_document_vars = NULL)
834 return $this->_find($_id, $fields, $use_document_vars, false);
838 // this findOne([$_id], [$fields], [$use_document_vars]) {{{
840 * See documentation for find()
842 * @return object this
844 final function findOne($_id = NULL, $fields = null, $use_document_vars = NULL)
846 return $this->_find($_id, $fields, $use_document_vars, false);
850 // mixed findOneValue($field, [$_id], [$use_document_vars]) {{{
852 * $field = the name of the field to return the value of
854 * For $_id and $use_document_vars, see documentation for find()
856 * @return mixed (value of the field)
858 final function findOneValue($field, $_id = NULL, $use_document_vars = NULL)
860 $this->findOne($_id, array($field), $use_document_vars);
862 // return the field value, or null if the record doesn't have it
863 if (isset($this[$field]))
865 return $this[$field];
874 // array findOneAssoc([$_id], [$fields], [$use_document_vars]) {{{
876 * Same as findOne, but returns the results in an associative array
880 final function findOneAssoc($_id = NULL, $fields = null, $use_document_vars = NULL)
882 return $this->findOne($_id, $fields, $use_document_vars)->getArray();
886 // object findOneObj([$_id], [$fields], [$use_document_vars]) {{{
888 * Same as findOne, but returns the results in an object (stdClass)
890 * @return object (stdClass)
892 final function findOneObj($_id = NULL, $fields = null, $use_document_vars = NULL)
894 return (object)$this->findOneAssoc($_id, $fields, $use_document_vars);
898 // array findAll([$_id], [$fields], [$use_document_vars]) {{{
900 * Same as find, but returns a single array with all the results at once.
902 * This should rarely ever be needed. Mostly useful for tasks such as
903 * quickly JSON encoding the whole result.
905 * @return array(this)
907 final function findAll($_id = NULL, $fields = null, $use_document_vars = NULL)
909 $cursor = $this->find($_id, $fields, $use_document_vars);
911 foreach($cursor as $row)
920 // array findAllAssoc([$_id], [$fields], [$use_document_vars]) {{{
922 * Same as findAll, but returns the rows as associative arrays
924 * This should rarely ever be needed. Mostly useful for tasks such as
925 * quickly JSON encoding the whole result.
927 * @return array(array)
929 final function findAllAssoc($_id = NULL, $fields = null, $use_document_vars = NULL)
931 $cursor = $this->find($_id, $fields, $use_document_vars);
933 foreach($cursor as $row)
935 $ret[] = $row->getArray();
942 // array findAllObj([$_id], [$fields], [$use_document_vars]) {{{
944 * Same as findAll, but returns the rows as objects (stdClass)
946 * This should rarely ever be needed. Mostly useful for tasks such as
947 * quickly JSON encoding the whole result.
949 * @return array(stdClass)
951 final function findAllObj($_id = NULL, $fields = null, $use_document_vars = NULL)
953 $cursor = $this->find($_id, $fields, $use_document_vars);
955 foreach($cursor as $row)
957 $ret[] = (object)$row->getArray();
964 // array findPairs($keyfield, $valuefield, [$_id], [$use_document_vars]) {{{
966 * returns an array of key value pairs, using the specified fields
967 * as the key and value. If the key is not unique the returned value
968 * will be the value for any one of the keys.
970 * If rows that do not contain a value in the key field will not be returned
972 * For $_id and $use_document_vars, see documentation for find()
976 final function findPairs($keyfield, $valuefield, $_id = NULL, $use_document_vars = NULL)
978 $cursor = $this->find($_id, array($keyfield, $valuefield), $use_document_vars);
980 foreach($cursor as $row)
982 if (isset($row[$keyfield]))
984 if (isset($row[$valuefield]))
986 $ret[] = $row[$valuefield];
999 // array findCol($field, [$_id], [$use_document_vars]) {{{
1001 * Same as findOneValue, but returns the the value for multiple rows as an array
1003 * The keys in the array are the record ids
1007 final function findCol($field, $_id = NULL, $use_document_vars = NULL)
1009 return $this->findPairs('_id', $field, $_id, $use_document_vars);
1013 // this _find([$_id], [$fields], [$use_document_vars], $findOne) {{{
1015 * See documentation for find()
1017 * when $findOne is false, a collection is loaded, when true, a single
1018 * result is loaded into this object, otherwise a cursor is loaded.
1020 * @return object this
1022 final function _find($_id = NULL, $fields = null, $use_document_vars = NULL, $findOne = false)
1026 if ($use_document_vars ||
($use_document_vars === NULL && $_id === NULL))
1028 $vars = get_document_vars($this);
1029 $parent_class = __CLASS__
;
1030 foreach ($vars as $key => $value) {
1034 if ($value InstanceOf $parent_class) {
1035 $this->getColumnDeference($vars, $key, $value);
1036 unset($vars[$key]); /* delete old value */
1045 $search_ids = array();
1047 foreach($_id as $k => $v)
1049 if ($loop_count != $k)
1051 $search_ids = false;
1055 // This is part of a list of IDs
1056 if (is_array($search_ids)) // true unless we found a reson to treat it differently
1069 if (is_array($search_ids) && count($search_ids))
1071 $vars['_id'] = array('$in' => $search_ids);
1074 $vars['_id'] = $_id;
1081 $fields = array(); // Mongo expects an array, not NULL
1083 else if (!is_array($fields))
1085 // probably a single field not placed in an array
1086 $fields = array($fields);
1092 $res = $this->_getCollection()->findOne($vars, $fields);
1093 $this->setResult($res);
1098 $res = $this->_getCollection()->find($vars, $fields);
1099 $this->setCursor($res);
1106 // void save(bool $async) {{{
1110 * This method save the current document in MongoDB. If
1111 * we're modifying a document, a update is performed, otherwise
1112 * the document is inserted.
1114 * On updates, special operations such as $set, $pushAll, $pullAll
1115 * and $unset in order to perform efficient updates
1117 * @param bool $async
1121 final function save($async=TRUE)
1123 $update = isset($this->_id
) && $this->_id
InstanceOf MongoID
;
1124 $conn = $this->_getCollection();
1125 $document = $this->getCurrentDocument($update);
1126 $object = $this->getDocumentVars();
1128 if (isset($this->_id
)) {
1129 $object['_id'] = $this->_id
;
1132 if (count($document) == 0) {
1133 return; /*nothing to do */
1137 $this->triggerEvent('before_'.($update ?
'update' : 'create'), array(&$document, $object));
1140 $conn->update(array('_id' => $this->_id
), $document, array('safe' => $async));
1141 if (isset($document['$set'])) {
1142 foreach ($document['$set'] as $key => $value) {
1143 if (strpos($key, ".") === FALSE) {
1144 $this->_current
[$key] = $value;
1145 $this->$key = $value;
1147 $keys = explode(".", $key);
1149 $arr = & $this->$key;
1150 $arrc = & $this->_current
[$key];
1151 for ($i=1; $i < count($keys)-1; $i++
) {
1152 $arr = &$arr[$keys[$i]];
1153 $arrc = &$arrc[$keys[$i]];
1155 $arr [ $keys[$i] ] = $value;
1156 $arrc[ $keys[$i] ] = $value;
1160 if (isset($document['$unset'])) {
1161 foreach ($document['$unset'] as $key => $value) {
1162 if (strpos($key, ".") === FALSE) {
1163 unset($this->_current
[$key]);
1166 $keys = explode(".", $key);
1168 $arr = & $this->$key;
1169 $arrc = & $this->_current
[$key];
1170 for ($i=1; $i < count($keys)-1; $i++
) {
1171 $arr = &$arr[$keys[$i]];
1172 $arrc = &$arrc[$keys[$i]];
1174 unset($arr [ $keys[$i] ]);
1175 unset($arrc[ $keys[$i] ]);
1180 $conn->insert($document, $async);
1181 $this->setResult($document);
1184 $this->triggerEvent('after_'.($update ?
'update' : 'create'), array($document, $object));
1190 // bool delete() {{{
1192 * Delete the current document
1196 final function delete()
1199 $document = array('_id' => $this->_id
);
1200 if ($this->_cursor
InstanceOf MongoCursor
) {
1201 $this->triggerEvent('before_delete', array($document));
1202 $result = $this->_getCollection()->remove($document);
1203 $this->triggerEvent('after_delete', array($document));
1204 $this->setResult(array());
1207 else if ($this->_cursor_ex
== self
::FIND_AND_MODIFY
&&
1208 !is_null($this->_cursor_ex_value
) &&
1209 $this->_cursor_ex_value
['ok'] == 1)
1212 $this->triggerEvent('before_delete', array($document));
1213 $result = $this->_getCollection()->remove($document);
1214 $this->triggerEvent('after_delete', array($document));
1215 $this->setResult(array());
1218 $criteria = (array) $this->_query
;
1221 $this->triggerEvent('before_delete', array($document));
1222 $this->_getCollection()->remove($criteria);
1223 $this->triggerEvent('after_delete', array($document));
1238 * This method perform multiple updates when a given
1239 * criteria matchs (using where).
1241 * By default the update is perform safely, but it can be
1244 * After the operation is done, the criteria is deleted.
1246 * @param array $value Values to set
1247 * @param bool $safe Whether or not peform the operation safely
1252 function update(Array $value, $safe=TRUE)
1254 $this->_assertNotInQuery();
1256 $criteria = (array) $this->_query
;
1257 $options = array('multiple' => TRUE, 'safe' => $safe);
1260 $col = $this->_getCollection();
1261 $col->update($criteria, array('$set' => $value), $options);
1272 * Delete the current colleciton and all its documents
1276 final static function drop()
1278 $class = get_called_class();
1279 if ($class == __CLASS__ || self
::isAbstractChildClass($class)) {
1283 $obj->triggerEvent('before_drop');
1284 $result = $obj->_getCollection()->drop();
1285 $obj->triggerEvent('after_drop');
1286 if ($result['ok'] != 1) {
1287 throw new ActiveMongo_Exception($result['errmsg']);
1296 * Return the number of documents in the actual request. If
1297 * we're not in a request, it will return 0.
1301 final function count()
1303 if ($this->valid()) {
1304 return $this->_cursor
->count();
1312 * This method should contain all the indexes, and shard keys
1313 * needed by the current collection. This try to make
1314 * installation on development environments easier.
1323 * Perform a batchInsert of objects.
1325 * @param array $documents Arrays of documents to insert
1326 * @param bool $safe True if a safe will be performed, this means data validation, and wait for MongoDB OK reply
1327 * @param bool $on_error_continue If an error happen while validating an object, if it should continue or not
1331 final public static function batchInsert(Array $documents, $safe=TRUE, $on_error_continue=TRUE)
1333 $context = get_called_class();
1335 if (__CLASS__
== $context || self
::isAbstractChildClass($context)) {
1336 throw new ActiveMongo_Exception("Invalid batchInsert usage");
1341 foreach ($documents as $id => $doc) {
1343 if (is_array($doc)) {
1345 self
::triggerEvent('before_create', array(&$doc), $context);
1346 self
::triggerEvent('before_validate', array(&$doc, $doc), $context);
1347 self
::triggerEvent('before_validate_creation', array(&$doc, $doc), $context);
1348 $documents[$id] = $doc;
1350 } catch (Exception
$e) {}
1353 if (!$on_error_continue) {
1354 throw new ActiveMongo_FilterException("Document $id is invalid");
1356 unset($documents[$id]);
1361 return self
::_getCollection()->batchInsert($documents, array("safe" => $safe));
1365 // bool addIndex(array $columns, array $options) {{{
1369 * Create an Index in the current collection.
1371 * @param array $columns L ist of columns
1372 * @param array $options Options
1376 final function addIndex($columns, $options=array())
1378 $default_options = array(
1382 if (!is_array($columns)) {
1383 $columns = array($columns => 1);
1386 foreach ($columns as $id => $name) {
1387 if (is_numeric($id)) {
1388 unset($columns[$id]);
1389 $columns[$name] = 1;
1393 foreach ($default_options as $option => $value) {
1394 if (!isset($options[$option])) {
1395 $options[$option] = $value;
1399 $collection = $this->_getCollection();
1401 return $collection->ensureIndex($columns, $options);
1405 // Array getIndexes() {{{
1407 * Return an array with all indexes
1411 final static function getIndexes()
1413 return self
::_getCollection()->getIndexInfo();
1417 // string __toString() {{{
1421 * If this object is treated as a string,
1422 * it would return its ID.
1426 function __toString()
1428 return (string)$this->getID();
1432 // array sendCmd(array $cmd) {{{
1434 * This method sends a command to the current
1437 * @param array $cmd Current command
1441 final protected function sendCmd($cmd)
1443 return $this->_getConnection()->command($cmd);
1449 // array getArray() {{{
1451 * Return the current document as an array
1452 * instead of a ActiveMongo object
1456 final function getArray()
1458 return get_document_vars($this);
1464 * Reset our Object, delete the current cursor if any, and reset
1465 * unsets the values.
1469 final function reset()
1471 if ($this->_cloned
) {
1472 throw new ActiveMongo_Exception("Cloned objects can't be reseted");
1474 $this->_properties
= NULL;
1475 $this->_cursor
= NULL;
1476 $this->_cursor_ex
= NULL;
1477 $this->_query
= NULL;
1478 $this->_sort
= NULL;
1481 $this->setResult(array());
1489 * Return if we're on an iteration and if it is still valid
1493 final function valid()
1496 if (!$this->_cursor_ex
) {
1497 if (!$this->_cursor
InstanceOf MongoCursor
) {
1500 $valid = $this->_cursor
InstanceOf MongoCursor
&& $this->_cursor
->valid();
1502 switch ($this->_cursor_ex
) {
1503 case self
::FIND_AND_MODIFY
:
1504 if ($this->_limit
> $this->_findandmodify_cnt
) {
1505 $this->_execFindAndModify();
1506 $valid = $this->_cursor_ex_value
['ok'] == 1;
1510 throw new ActiveMongo_Exception("Invalid _cursor_ex value");
1520 * Move to the next document
1524 final function next()
1526 if ($this->_cloned
) {
1527 throw new ActiveMongo_Exception("Cloned objects can't iterate");
1529 if (!$this->_cursor_ex
) {
1530 $result = $this->_cursor
->next();
1534 switch ($this->_cursor_ex
) {
1535 case self
::FIND_AND_MODIFY
:
1536 $this->_cursor_ex_value
= NULL;
1539 throw new ActiveMongo_Exception("Invalid _cursor_ex value");
1545 // this current() {{{
1547 * Return the current object, and load the current document
1548 * as this object property
1552 final function current()
1554 if (!$this->_cursor_ex
) {
1555 $this->setResult($this->_cursor
->current());
1557 switch ($this->_cursor_ex
) {
1558 case self
::FIND_AND_MODIFY
:
1559 if (count($this->_cursor_ex_value
) == 0) {
1560 $this->_execFindAndModify();
1562 $this->setResult($this->_cursor_ex_value
['value']);
1565 throw new ActiveMongo_Exception("Invalid _cursor_ex value");
1572 // bool rewind() {{{
1574 * Go to the first document
1576 final function rewind()
1578 if ($this->_cloned
) {
1579 throw new ActiveMongo_Exception("Cloned objects can't iterate");
1581 if (!$this->_cursor_ex
) {
1582 /* rely on MongoDB cursor */
1583 if (!$this->_cursor
InstanceOf MongoCursor
) {
1586 $result = $this->_cursor
->rewind();
1590 switch ($this->_cursor_ex
) {
1591 case self
::FIND_AND_MODIFY
:
1592 $this->_findandmodify_cnt
= 0;
1595 throw new ActiveMongo_Exception("Invalid _cursor_ex value");
1604 final function offsetExists($offset)
1606 return isset($this->$offset);
1609 final function offsetGet($offset)
1611 return $this->$offset;
1614 final function offsetSet($offset, $value)
1616 $this->$offset = $value;
1619 final function offsetUnset($offset)
1621 unset($this->$offset);
1627 // array getReference() {{{
1629 * ActiveMongo extended the Mongo references, adding
1630 * the concept of 'dynamic' requests, saving in the database
1631 * the current query with its options (sort, limit, etc).
1633 * This is useful to associate a document with a given
1634 * request. To undestand this better please see the 'reference'
1639 final function getReference($dynamic=FALSE)
1641 if (!$this->getID() && !$dynamic) {
1646 '$ref' => $this->CollectionName(),
1647 '$id' => $this->getID(),
1648 '$db' => $this->getDatabaseName(),
1649 'class' => get_class($this),
1653 if (!$this->_cursor
InstanceOf MongoCursor
&& $this->_cursor_ex
=== NULL) {
1657 if (!$this->_cursor
InstanceOf MongoCursor
) {
1658 throw new ActiveMongo_Exception("Only MongoDB native cursor could have dynamic references");
1661 $cursor = $this->_cursor
;
1662 if (!is_callable(array($cursor, "Info"))) {
1663 throw new Exception("Please upgrade your PECL/Mongo module to use this feature");
1665 $document['dynamic'] = array();
1666 $query = $cursor->Info();
1667 foreach ($query as $type => $value) {
1668 $document['dynamic'][$type] = $value;
1675 // void getDocumentReferences($document, &$refs) {{{
1677 * Get Current References
1679 * Inspect the current document trying to get any references,
1682 * @param array $document Current document
1683 * @param array &$refs References found in the document.
1684 * @param array $parent_key Parent key
1688 final protected function getDocumentReferences($document, &$refs, $parent_key=NULL)
1690 foreach ($document as $key => $value) {
1691 if (is_array($value)) {
1692 if (MongoDBRef
::isRef($value)) {
1693 $pkey = $parent_key;
1695 $refs[] = array('ref' => $value, 'key' => $pkey);
1697 $parent_key1 = $parent_key;
1698 $parent_key1[] = $key;
1699 $this->getDocumentReferences($value, $refs, $parent_key1);
1706 // object _deferencingCreateObject(string $class) {{{
1708 * Called at deferencig time
1710 * Check if the given string is a class, and it is a sub class
1711 * of ActiveMongo, if it is instance and return the object.
1713 * @param string $class
1717 private function _deferencingCreateObject($class)
1719 if (!is_subclass_of($class, __CLASS__
)) {
1720 throw new ActiveMongo_Exception("Fatal Error, imposible to create ActiveMongo object of {$class}");
1726 // void _deferencingRestoreProperty(array &$document, array $keys, mixed $req) {{{
1728 * Called at deferencig time
1730 * This method iterates $document until it could match $keys path, and
1731 * replace its value by $req.
1733 * @param array &$document Document to replace
1734 * @param array $keys Path of property to change
1735 * @param mixed $req Value to replace.
1739 private function _deferencingRestoreProperty(&$document, $keys, $req)
1743 /* find the $req proper spot */
1744 foreach ($keys as $key) {
1745 $obj = & $obj[$key];
1750 /* Delete reference variable */
1755 // object _deferencingQuery($request) {{{
1757 * Called at deferencig time
1759 * This method takes a dynamic reference and request
1762 * @param array $request Dynamic reference
1766 private function _deferencingQuery($request)
1768 $collection = $this->_getCollection();
1769 $cursor = $collection->find($request['query'], $request['fields']);
1770 if ($request['limit'] > 0) {
1771 $cursor->limit($request['limit']);
1773 if ($request['skip'] > 0) {
1774 $cursor->skip($request['skip']);
1777 $this->setCursor($cursor);
1783 // void doDeferencing() {{{
1785 * Perform a deferencing in the current document, if there is
1788 * ActiveMongo will do its best to group references queries as much
1789 * as possible, in order to perform as less request as possible.
1791 * ActiveMongo doesn't rely on MongoDB references, but it can support
1792 * it, but it is prefered to use our referencing.
1796 final function doDeferencing($refs=array())
1798 /* Get current document */
1799 $document = get_document_vars($this);
1801 if (count($refs)==0) {
1802 /* Inspect the whole document */
1803 $this->getDocumentReferences($document, $refs);
1806 $db = $this->_getConnection();
1808 /* Gather information about ActiveMongo Objects
1809 * that we need to create
1812 foreach ($refs as $ref) {
1813 if (!isset($ref['ref']['class'])) {
1815 /* Support MongoDBRef, we do our best to be compatible {{{ */
1816 /* MongoDB 'normal' reference */
1818 $obj = MongoDBRef
::get($db, $ref['ref']);
1820 /* Offset the current document to the right spot */
1821 /* Very inefficient, never use it, instead use ActiveMongo References */
1823 $this->_deferencingRestoreProperty($document, $ref['key'], $obj);
1825 /* Dirty hack, override our current document
1826 * property with the value itself, in order to
1827 * avoid replace a MongoDB reference by its content
1829 $this->_deferencingRestoreProperty($this->_current
, $ref['key'], $obj);
1835 if (isset($ref['ref']['dynamic'])) {
1836 /* ActiveMongo Dynamic Reference */
1838 /* Create ActiveMongo object */
1839 $req = $this->_deferencingCreateObject($ref['ref']['class']);
1841 /* Restore saved query */
1842 $req->_deferencingQuery($ref['ref']['dynamic']);
1846 /* Add the result set */
1847 foreach ($req as $result) {
1848 $results[] = clone $result;
1851 /* add information about the current reference */
1852 foreach ($ref['ref'] as $key => $value) {
1853 $results[$key] = $value;
1856 $this->_deferencingRestoreProperty($document, $ref['key'], $results);
1859 /* ActiveMongo Reference FTW! */
1860 $classes[$ref['ref']['class']][] = $ref;
1865 /* {{{ Create needed objects to query MongoDB and replace
1866 * our references by its objects documents.
1868 foreach ($classes as $class => $refs) {
1869 $req = $this->_deferencingCreateObject($class);
1871 /* Load list of IDs */
1873 foreach ($refs as $ref) {
1874 $ids[] = $ref['ref']['$id'];
1877 /* Search to MongoDB once for all IDs found */
1881 /* Replace our references by its objects */
1882 foreach ($refs as $ref) {
1883 $id = $ref['ref']['$id'];
1884 $place = $ref['key'];
1885 foreach ($req as $item) {
1886 if ($item->getID() == $id) {
1887 $this->_deferencingRestoreProperty($document, $place, clone $req);
1893 /* Release request, remember we
1900 /* Replace the current document by the new deferenced objects */
1901 foreach ($document as $key => $value) {
1902 $this->$key = $value;
1907 // void getColumnDeference(&$document, $propety, ActiveMongo Obj) {{{
1909 * Prepare a "selector" document to search treaing the property
1910 * as a reference to the given ActiveMongo object.
1913 final function getColumnDeference(&$document, $property, ActiveMongo
$obj)
1915 $document["{$property}.\$id"] = $obj->getID();
1919 // void findReferences(&$document) {{{
1921 * Check if in the current document to insert or update
1922 * exists any references to other ActiveMongo Objects.
1926 final function findReferences(&$document)
1928 if (!is_array($document)) {
1931 foreach($document as &$value) {
1932 $parent_class = __CLASS__
;
1933 if (is_array($value)) {
1934 if (MongoDBRef
::isRef($value)) {
1935 /* If the property we're inspecting is a reference,
1936 * we need to remove the values, restoring the valid
1940 '$ref'=>1, '$id'=>1, '$db'=>1, 'class'=>1, 'dynamic'=>1
1942 foreach (array_keys($value) as $key) {
1943 if (!isset($arr[$key])) {
1944 unset($value[$key]);
1948 $this->findReferences($value);
1950 } else if ($value InstanceOf $parent_class) {
1951 $value = $value->getReference();
1954 /* trick: delete last var. reference */
1959 // void __clone() {{{
1961 * Cloned objects are rarely used, but ActiveMongo
1962 * uses it to create different objects per everyrecord,
1963 * which is used at deferencing. Therefore cloned object
1964 * do not contains the recordset, just the actual document,
1965 * so iterations are not allowed.
1968 final function __clone()
1970 if (!$this->_current
) {
1971 throw new ActiveMongo_Exception("Empty objects can't be cloned");
1973 unset($this->_cursor
);
1974 $this->_cloned
= TRUE;
1980 // GET DOCUMENT ID {{{
1984 * Return the current document ID. If there is
1985 * no document it would return FALSE.
1987 * @return object|FALSE
1989 final public function getID()
1991 if ($this->_id
instanceof MongoID
) {
2000 * Return the current key
2004 final function key()
2006 return (string)$this->getID();
2012 // Fancy (and silly) query abstraction {{{
2014 // _assertNotInQuery() {{{
2016 * Check if we can modify the query or not. We cannot modify
2017 * the query if we're iterating over and oldest query, in this case the
2018 * object must be reset.
2022 final private function _assertNotInQuery()
2024 if ($this->_cloned ||
$this->_cursor
InstanceOf MongoCursor ||
$this->_cursor_ex
!= NULL) {
2025 throw new ActiveMongo_Exception("You cannot modify the query, please reset the object");
2030 // bool servedFromCache() {{{
2032 * Return True if the current result
2033 * was provided by a before_query hook (aka cache)
2034 * or False if it was retrieved from MongoDB
2038 final function servedFromCache()
2040 return $this->_cached
;
2046 * Build the current request and send it to MongoDB.
2050 final function doQuery($use_cache=TRUE)
2052 if ($this->_cursor_ex
) {
2053 switch ($this->_cursor_ex
) {
2054 case self
::FIND_AND_MODIFY
:
2055 $this->_cursor_ex_value
= NULL;
2058 throw new ActiveMongo_Exception("Invalid _cursor_ex value");
2061 $this->_assertNotInQuery();
2064 'collection' => $this->CollectionName(),
2065 'query' => (array)$this->_query
,
2066 'properties' => (array)$this->_properties
,
2067 'sort' => (array)$this->_sort
,
2068 'skip' => $this->_skip
,
2069 'limit' => $this->_limit
2072 $this->_cached
= FALSE;
2074 self
::triggerEvent('before_query', array(&$query, &$documents, $use_cache));
2076 if ($documents InstanceOf MongoCursor
&& $use_cache) {
2077 $this->_cached
= TRUE;
2078 $this->setCursor($documents);
2082 $col = $this->_getCollection();
2083 if (count($query['properties']) > 0) {
2084 $cursor = $col->find($query['query'], $query['properties']);
2086 $cursor = $col->find($query['query']);
2088 if (count($query['sort']) > 0) {
2089 $cursor->sort($query['sort']);
2091 if ($query['limit'] > 0) {
2092 $cursor->limit($query['limit']);
2094 if ($query['skip'] > 0) {
2095 $cursor->skip($query['skip']);
2098 self
::triggerEvent('after_query', array($query, $cursor));
2100 /* Our cursor must be sent to ActiveMongo */
2101 $this->setCursor($cursor);
2107 // properties($props) {{{
2109 * Select 'properties' or 'columns' to be included in the document,
2110 * by default all properties are included.
2112 * @param array $props
2116 final function properties($props)
2118 $this->_assertNotInQuery();
2120 if (!is_array($props) && !is_string($props)) {
2124 if (is_string($props)) {
2125 $props = explode(",", $props);
2128 foreach ($props as $id => $name) {
2129 $props[trim($name)] = 1;
2134 /* _id should always be included */
2137 $this->_properties
= $props;
2142 final function columns($properties)
2144 return $this->properties($properties);
2148 // where($property, $value) {{{
2150 * Where abstraction.
2153 final function where($property_str, $value=NULL)
2155 $this->_assertNotInQuery();
2157 if (is_array($property_str)) {
2158 if ($value != NULL) {
2159 throw new ActiveMongo_Exception("Invalid parameters");
2161 foreach ($property_str as $property => $value) {
2162 if (is_numeric($property)) {
2166 $this->where($property, $value);
2171 $column = explode(" ", trim($property_str));
2172 if (count($column) != 1 && count($column) != 2) {
2173 throw new ActiveMongo_Exception("Failed while parsing '{$property_str}'");
2174 } else if (count($column) == 2) {
2177 switch (strtolower($column[1])) {
2201 if (is_array($value)) {
2203 $exp_scalar = FALSE;
2212 if (is_array($value)) {
2214 $exp_scalar = FALSE;
2224 $exp_scalar = FALSE;
2229 if ($value === NULL) {
2238 $value = new MongoRegex($value);
2245 $exp_scalar = FALSE;
2251 $exp_scalar = FALSE;
2256 /* geo operations */
2260 $exp_scalar = FALSE;
2264 throw new ActiveMongo_Exception("Failed to parse '{$column[1]}'");
2267 if ($exp_scalar && is_array($value)) {
2268 throw new ActiveMongo_Exception("Cannot use comparing operations with Array");
2269 } else if (!$exp_scalar && !is_array($value)) {
2270 throw new ActiveMongo_Exception("The operation {$column[1]} expected an Array");
2274 $value = array($op => $value);
2276 } else if (is_array($value)) {
2277 $value = array('$in' => $value);
2280 $spot = & $this->_query
[$column[0]];
2281 if (is_array($spot) && is_array($value)) {
2282 $spot[key($value)] = current($value);
2284 /* simulate AND among same properties if
2285 * multiple values is passed for same property
2288 if (is_array($spot)) {
2289 $spot['$all'][] = $value;
2291 $spot = array('$all' => array($spot, $value));
2302 // sort($sort_str) {{{
2304 * Abstract the documents sorting.
2306 * @param string $sort_str List of properties to use as sorting
2310 final function sort($sort_str)
2312 $this->_assertNotInQuery();
2314 $this->_sort
= array();
2315 foreach ((array)explode(",", $sort_str) as $sort_part_str) {
2316 $sort_part = explode(" ", trim($sort_part_str), 2);
2317 switch(count($sort_part)) {
2319 $sort_part[1] = 'ASC';
2324 throw new ActiveMongo_Exception("Don't know how to parse {$sort_part_str}");
2327 /* Columns name can't be empty */
2328 if (!trim($sort_part[0])) {
2329 throw new ActiveMongo_Exception("Don't know how to parse {$sort_part_str}");
2332 switch (strtoupper($sort_part[1])) {
2340 throw new ActiveMongo_Exception("Invalid sorting direction `{$sort_part[1]}`");
2342 $this->_sort
[ $sort_part[0] ] = $sort_part[1];
2349 // limit($limit, $skip) {{{
2351 * Abstract the limitation and pagination of documents.
2353 * @param int $limit Number of max. documents to retrieve
2354 * @param int $skip Number of documents to skip
2358 final function limit($limit=0, $skip=0)
2360 $this->_assertNotInQuery();
2362 if ($limit < 0 ||
$skip < 0) {
2365 $this->_limit
= $limit;
2366 $this->_skip
= $skip;
2372 // FindAndModify(Array $document) {{{
2378 final function findAndModify($document)
2380 $this->_assertNotInQuery();
2382 if (count($document) === 0) {
2383 throw new ActiveMongo_Exception("Empty \$document is not allowed");
2386 $this->_cursor_ex
= self
::FIND_AND_MODIFY
;
2387 $this->_findandmodify
= $document;
2392 private function _execFindAndModify()
2394 $query = (array)$this->_query
;
2397 "findandmodify" => $this->CollectionName(),
2399 "update" => array('$set' => $this->_findandmodify
),
2402 if (isset($this->_sort
)) {
2403 $query["sort"] = $this->_sort
;
2405 $this->_cursor_ex_value
= $this->sendCMD($query);
2407 $this->_findandmodify_cnt++
;
2415 * Return a list of properties to serialize, to save
2422 return array_keys(get_document_vars($this));
2428 require_once dirname(__FILE__
)."/Validators.php";
2429 require_once dirname(__FILE__
)."/Exceptions.php";
2436 * vim600: sw=4 ts=4 fdm=marker
2437 * vim<600: sw=4 ts=4