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 // Class FilterException {{{
39 class ActiveMongo_Exception
extends Exception
45 * This is Exception is thrown if any validation
46 * fails when save() is called.
49 class ActiveMongo_FilterException
extends ActiveMongo_Exception
54 // array get_object_vars_ex(stdobj $obj) {{{
56 * Simple hack to avoid get private and protected variables
62 function get_object_vars_ex($obj)
64 return get_object_vars($obj);
71 * Simple ActiveRecord pattern built on top of MongoDB. This class
72 * aims to provide easy iteration, data validation before update,
73 * and efficient update.
75 * @author César D. Rodas <crodas@php.net>
76 * @license PHP License
77 * @package ActiveMongo
81 abstract class ActiveMongo
implements Iterator
86 * Current databases objects
92 * Current collections objects
96 private static $_collections;
98 * Current connection to MongoDB
100 * @type MongoConnection
102 private static $_conn;
110 * List of events handlers
114 static private $_events = array();
116 * List of global events handlers
120 static private $_super_events = array();
126 private static $_host;
132 private $_current = array();
138 private $_cursor = null;
140 /* {{{ Silly but useful query abstraction */
141 private $_query = null;
142 private $_sort = null;
145 private $_columns = null;
149 * Current document ID
156 * Tell if the current object
161 private $_cloned = false;
164 // GET CONNECTION CONFIG {{{
166 // string getCollectionName() {{{
168 * Get Collection Name, by default the class name,
169 * but you it can be override at the class itself to give
172 * @return string Collection Name
174 protected function getCollectionName()
176 return strtolower(get_class($this));
180 // string getDatabaseName() {{{
182 * Get Database Name, by default it is used
183 * the db name set by ActiveMong::connect()
185 * @return string DB Name
187 protected function getDatabaseName()
189 if (is_null(self
::$_db)) {
190 throw new MongoException("There is no information about the default DB name");
196 // void install() {{{
200 * This static method iterate over the classes lists,
201 * and execute the setup() method on every ActiveMongo
202 * subclass. You should do this just once.
205 final public static function install()
207 $classes = array_reverse(get_declared_classes());
208 foreach ($classes as $class)
210 if ($class == __CLASS__
) {
213 if (is_subclass_of($class, __CLASS__
)) {
221 // void connection($db, $host) {{{
225 * This method setup parameters to connect to a MongoDB
226 * database. The connection is done when it is needed.
228 * @param string $db Database name
229 * @param string $host Host to connect
233 final public static function connect($db, $host='localhost')
235 self
::$_host = $host;
240 // MongoConnection _getConnection() {{{
244 * Get a valid database connection
246 * @return MongoConnection
248 final protected function _getConnection()
250 if (is_null(self
::$_conn)) {
251 if (is_null(self
::$_host)) {
252 self
::$_host = 'localhost';
254 self
::$_conn = new Mongo(self
::$_host);
256 $dbname = $this->getDatabaseName();
257 if (!isSet(self
::$_dbs[$dbname])) {
258 self
::$_dbs[$dbname] = self
::$_conn->selectDB($dbname);
260 return self
::$_dbs[$dbname];
264 // MongoCollection _getCollection() {{{
268 * Get a collection connection.
270 * @return MongoCollection
272 final protected function _getCollection()
274 $colName = $this->getCollectionName();
275 if (!isset(self
::$_collections[$colName])) {
276 self
::$_collections[$colName] = self
::_getConnection()->selectCollection($colName);
278 return self
::$_collections[$colName];
284 // GET DOCUMENT TO SAVE OR UPDATE {{{
286 // bool getCurrentSubDocument(array &$document, string $parent_key, array $values, array $past_values) {{{
288 * Generate Sub-document
290 * This method build the difference between the current sub-document,
291 * and the origin one. If there is no difference, it would do nothing,
292 * otherwise it would build a document containing the differences.
294 * @param array &$document Document target
295 * @param string $parent_key Parent key name
296 * @param array $values Current values
297 * @param array $past_values Original values
301 final function getCurrentSubDocument(&$document, $parent_key, Array $values, Array $past_values)
304 * The current property is a embedded-document,
305 * now we're looking for differences with the
306 * previous value (because we're on an update).
308 * It behaves exactly as getCurrentDocument,
309 * but this is simples (it doesn't support
312 foreach ($values as $key => $value) {
313 $super_key = "{$parent_key}.{$key}";
314 if (is_array($value)) {
316 * Inner document detected
318 if (!isset($past_values[$key]) ||
!is_array($past_values[$key])) {
320 * We're lucky, it is a new sub-document,
323 $document['$set'][$super_key] = $value;
326 * This is a document like this, we need
327 * to find out the differences to avoid
330 if (!$this->getCurrentSubDocument($document, $super_key, $value, $past_values[$key])) {
335 } else if (!isset($past_values[$key]) ||
$past_values[$key] != $value) {
336 $document['$set'][$super_key] = $value;
340 foreach (array_diff(array_keys($past_values), array_keys($values)) as $key) {
341 $super_key = "{$parent_key}.{$key}";
342 $document['$unset'][$super_key] = 1;
349 // array getCurrentDocument(bool $update) {{{
351 * Get Current Document
353 * Based on this object properties a new document (Array)
354 * is returned. If we're modifying an document, just the modified
355 * properties are included in this document, which uses $set,
356 * $unset, $pushAll and $pullAll.
359 * @param bool $update
363 final protected function getCurrentDocument($update=false, $current=false)
366 $object = get_object_vars_ex($this);
369 $current = (array)$this->_current
;
373 $this->findReferences($object);
375 $this->triggerEvent('before_validate_'.($update?
'update':'creation'), array(&$object));
376 $this->triggerEvent('before_validate', array(&$object));
378 foreach ($object as $key => $value) {
383 if (is_array($value) && isset($current[$key])) {
385 * If the Field to update is an array, it has a different
386 * behaviour other than $set and $unset. Fist, we need
387 * need to check if it is an array or document, because
388 * they can't be mixed.
391 if (!is_array($current[$key])) {
393 * We're lucky, the field wasn't
394 * an array previously.
396 $this->runFilter($key, $value, $current[$key]);
397 $document['$set'][$key] = $value;
401 if (!$this->getCurrentSubDocument($document, $key, $value, $current[$key])) {
402 throw new Exception("{$key}: Array and documents are not compatible");
404 } else if(!isset($current[$key]) ||
$value !== $current[$key]) {
406 * It is 'linear' field that has changed, or
409 $past_value = isset($current[$key]) ?
$current[$key] : null;
410 $this->runFilter($key, $value, $past_value);
411 $document['$set'][$key] = $value;
415 * It is a document insertation, so we
416 * create the document.
418 $this->runFilter($key, $value, null);
419 $document[$key] = $value;
423 /* Updated behaves in a diff. way */
425 foreach (array_diff(array_keys($this->_current
), array_keys($object)) as $property) {
426 if ($property == '_id') {
429 $document['$unset'][$property] = 1;
433 if (count($document) == 0) {
437 $this->triggerEvent('after_validate_'.($update?
'update':'creation'), array(&$object));
438 $this->triggerEvent('after_validate', array(&$document));
446 // EVENT HANDLERS {{{
448 // addEvent($action, $callback) {{{
453 final static function addEvent($action, $callback)
455 if (!is_callable($callback)) {
456 throw new Exception("Invalid callback");
459 $class = get_called_class();
460 if ($class == __CLASS__
) {
461 $events = & self
::$_super_events;
463 $events = & self
::$_events[$class];
465 if (!isset($events[$action])) {
466 $events[$action] = array();
468 $events[$action][] = $callback;
473 // triggerEvent(string $event, Array $events_params) {{{
474 final function triggerEvent($event, Array $events_params = array())
476 $events = & self
::$_events[get_class($this)][$event];
477 $sevents = & self
::$_super_events[$event];
479 if (!is_array($events_params)) {
483 /* Super-Events handler receives the ActiveMongo class name as first param */
484 $sevents_params = array_merge(array(get_class($this)), $events_params);
486 foreach (array('events', 'sevents') as $event_type) {
487 if (count($
$event_type) > 0) {
488 $params = "{$event_type}_params";
489 foreach ($
$event_type as $fnc) {
490 call_user_func_array($fnc, $
$params);
495 /* Some natives events are allowed to be called
496 * as methods, if they exists
499 case 'before_create':
500 case 'before_update':
501 case 'before_validate':
502 case 'before_delete':
505 case 'after_validate':
507 $fnc = array($this, $event);
508 $params = "events_params";
509 if (is_callable($fnc)) {
510 call_user_func_array($fnc, $
$params);
517 // void runFilter(string $key, mixed &$value, mixed $past_value) {{{
521 * This method check if the current document property has
522 * a filter method, if so, call it.
524 * If the filter returns false, throw an Exception.
528 protected function runFilter($key, &$value, $past_value)
530 $filter = array($this, "{$key}_filter");
531 if (is_callable($filter)) {
532 $filter = call_user_func_array($filter, array(&$value, $past_value));
533 if ($filter===false) {
534 throw new ActiveMongo_FilterException("{$key} filter failed");
536 $this->$key = $value;
543 // void setCursor(MongoCursor $obj) {{{
547 * This method receive a MongoCursor and make
550 * @param MongoCursor $obj
554 final protected function setCursor(MongoCursor
$obj)
556 $this->_cursor
= $obj;
557 $this->setResult($obj->getNext());
561 // void setResult(Array $obj) {{{
565 * This method takes an document and copy it
566 * as properties in this object.
572 final protected function setResult($obj)
574 /* Unsetting previous results, if any */
575 foreach (array_keys((array)$this->_current
) as $key) {
579 /* Add our current resultset as our object's property */
580 foreach ((array)$obj as $key => $value) {
581 if ($key[0] == '$') {
584 $this->$key = $value;
587 /* Save our record */
588 $this->_current
= $obj;
592 // this find([$_id]) {{{
596 * Really simple find, which uses this object properties
599 * @return object this
601 final function find($_id = null)
603 $vars = get_object_vars_ex($this);
604 foreach ($vars as $key => $value) {
608 $parent_class = __CLASS__
;
609 if ($value InstanceOf $parent_class) {
610 $this->getColumnDeference($vars, $key, $value);
611 unset($vars[$key]); /* delete old value */
615 if (is_array($_id)) {
616 $vars['_id'] = array('$in' => $_id);
621 $res = $this->_getCollection()->find($vars);
622 $this->setCursor($res);
627 // void save(bool $async) {{{
631 * This method save the current document in MongoDB. If
632 * we're modifying a document, a update is performed, otherwise
633 * the document is inserted.
635 * On updates, special operations such as $set, $pushAll, $pullAll
636 * and $unset in order to perform efficient updates
642 final function save($async=true)
644 $update = isset($this->_id
) && $this->_id
InstanceOf MongoID
;
645 $conn = $this->_getCollection();
646 $obj = $this->getCurrentDocument($update);
647 if (count($obj) == 0) {
648 return; /*nothing to do */
652 $this->triggerEvent('before_'.($update ?
'update' : 'create'), array(&$obj));
655 $conn->update(array('_id' => $this->_id
), $obj);
656 foreach ($obj as $key => $value) {
657 if ($key[0] == '$') {
660 $this->_current
[$key] = $value;
663 $conn->insert($obj, $async);
664 $this->_id
= $obj['_id'];
665 $this->_current
= $obj;
668 $this->triggerEvent('after_'.($update ?
'update' : 'create'), array($obj));
674 * Delete the current document
678 final function delete()
680 if ($this->valid()) {
681 $document = array('_id' => $this->_id
);
682 $this->triggerEvent('before_delete', array($document));
683 $result = $this->_getCollection()->remove($document);
684 $this->triggerEvent('after_delete', array($document));
693 * Delete the current colleciton and all its documents
697 final static function drop()
699 $class = get_called_class();
700 if ($class == __CLASS__
) {
704 return $obj->_getCollection()->drop();
710 * Return the number of documents in the actual request. If
711 * we're not in a request, it will return 0.
715 final function count()
717 if ($this->valid()) {
718 return $this->_cursor
->count();
726 * This method should contain all the indexes, and shard keys
727 * needed by the current collection. This try to make
728 * installation on development environments easier.
735 // bool addIndex(array $columns, array $options) {{{
739 * Create an Index in the current collection.
741 * @param array $columns L ist of columns
742 * @param array $options Options
746 final function addIndex($columns, $options=array())
748 $default_options = array(
752 foreach ($default_options as $option => $value) {
753 if (!isset($options[$option])) {
754 $options[$option] = $value;
758 $collection = $this->_getCollection();
760 return $collection->ensureIndex($columns, $options);
764 // string __toString() {{{
768 * If this object is treated as a string,
769 * it would return its ID.
773 final function __toString()
775 return (string)$this->getID();
779 // array sendCmd(array $cmd) {{{
781 * This method sends a command to the current
784 * @param array $cmd Current command
788 final protected function sendCmd($cmd)
790 return $this->_getConnection()->command($cmd);
798 * Reset our Object, delete the current cursor if any, and reset
803 final function reset()
805 $this->_columns
= null;
806 $this->_cursor
= null;
807 $this->_query
= null;
811 $this->setResult(array());
819 * Return if we're on an iteration and if it is still valid
823 final function valid()
825 return $this->_cursor
InstanceOf MongoCursor
&& $this->_cursor
->valid();
831 * Move to the next document
835 final function next()
837 if ($this->_cloned
) {
838 throw new MongoException("Cloned objects can't iterate");
840 return $this->_cursor
->next();
844 // this current() {{{
846 * Return the current object, and load the current document
847 * as this object property
851 final function current()
853 $this->setResult($this->_cursor
->current());
860 * Go to the first document
862 final function rewind()
864 if (!$this->_cursor
InstanceOf MongoCursor
) {
867 return $this->_cursor
->rewind();
875 // array getReference() {{{
877 * ActiveMongo extended the Mongo references, adding
878 * the concept of 'dynamic' requests, saving in the database
879 * the current query with its options (sort, limit, etc).
881 * This is useful to associate a document with a given
882 * request. To undestand this better please see the 'reference'
887 final function getReference($dynamic=false)
889 if (!$this->getID() && !$dynamic) {
894 '$ref' => $this->getCollectionName(),
895 '$id' => $this->getID(),
896 '$db' => $this->getDatabaseName(),
897 'class' => get_class($this),
900 if ($dynamic && $this->_cursor
InstanceOf MongoCursor
) {
901 $cursor = $this->_cursor
;
902 if (!is_callable(array($cursor, "Info"))) {
903 throw new Exception("Please upgrade your PECL/Mongo module to use this feature");
905 $document['dynamic'] = array();
906 $query = $cursor->Info();
907 foreach ($query as $type => $value) {
908 $document['dynamic'][$type] = $value;
915 // void getDocumentReferences($document, &$refs) {{{
917 * Get Current References
919 * Inspect the current document trying to get any references,
922 * @param array $document Current document
923 * @param array &$refs References found in the document.
924 * @param array $parent_key Parent key
928 final protected function getDocumentReferences($document, &$refs, $parent_key=null)
930 foreach ($document as $key => $value) {
931 if (is_array($value)) {
932 if (MongoDBRef
::isRef($value)) {
935 $refs[] = array('ref' => $value, 'key' => $pkey);
937 $parent_key[] = $key;
938 $this->getDocumentReferences($value, $refs, $parent_key);
945 // object _deferencingCreateObject(string $class) {{{
947 * Called at deferencig time
949 * Check if the given string is a class, and it is a sub class
950 * of ActiveMongo, if it is instance and return the object.
952 * @param string $class
956 private function _deferencingCreateObject($class)
958 if (!is_subclass_of($class, __CLASS__
)) {
959 throw new MongoException("Fatal Error, imposible to create ActiveMongo object of {$class}");
965 // void _deferencingRestoreProperty(array &$document, array $keys, mixed $req) {{{
967 * Called at deferencig time
969 * This method iterates $document until it could match $keys path, and
970 * replace its value by $req.
972 * @param array &$document Document to replace
973 * @param array $keys Path of property to change
974 * @param mixed $req Value to replace.
978 private function _deferencingRestoreProperty(&$document, $keys, $req)
982 /* find the $req proper spot */
983 foreach ($keys as $key) {
989 /* Delete reference variable */
994 // object _deferencingQuery($request) {{{
996 * Called at deferencig time
998 * This method takes a dynamic reference and request
1001 * @param array $request Dynamic reference
1005 private function _deferencingQuery($request)
1007 $collection = $this->_getCollection();
1008 $cursor = $collection->find($request['query'], $request['fields']);
1009 if ($request['limit'] > 0) {
1010 $cursor->limit($request['limit']);
1012 if ($request['skip'] > 0) {
1013 $cursor->limit($request['limit']);
1016 $this->setCursor($cursor);
1022 // void doDeferencing() {{{
1024 * Perform a deferencing in the current document, if there is
1027 * ActiveMongo will do its best to group references queries as much
1028 * as possible, in order to perform as less request as possible.
1030 * ActiveMongo doesn't rely on MongoDB references, but it can support
1031 * it, but it is prefered to use our referencing.
1035 final function doDeferencing($refs=array())
1037 /* Get current document */
1038 $document = get_object_vars_ex($this);
1040 if (count($refs)==0) {
1041 /* Inspect the whole document */
1042 $this->getDocumentReferences($document, $refs);
1045 $db = $this->_getConnection();
1047 /* Gather information about ActiveMongo Objects
1048 * that we need to create
1051 foreach ($refs as $ref) {
1052 if (!isset($ref['ref']['class'])) {
1054 /* Support MongoDBRef, we do our best to be compatible {{{ */
1055 /* MongoDB 'normal' reference */
1057 $obj = MongoDBRef
::get($db, $ref['ref']);
1059 /* Offset the current document to the right spot */
1060 /* Very inefficient, never use it, instead use ActiveMongo References */
1062 $this->_deferencingRestoreProperty($document, $ref['key'], clone $req);
1064 /* Dirty hack, override our current document
1065 * property with the value itself, in order to
1066 * avoid replace a MongoDB reference by its content
1068 $this->_deferencingRestoreProperty($this->_current
, $ref['key'], clone $req);
1074 if (isset($ref['ref']['dynamic'])) {
1075 /* ActiveMongo Dynamic Reference */
1077 /* Create ActiveMongo object */
1078 $req = $this->_deferencingCreateObject($ref['ref']['class']);
1080 /* Restore saved query */
1081 $req->_deferencingQuery($ref['ref']['dynamic']);
1085 /* Add the result set */
1086 foreach ($req as $result) {
1087 $results[] = clone $result;
1090 /* add information about the current reference */
1091 foreach ($ref['ref'] as $key => $value) {
1092 $results[$key] = $value;
1095 $this->_deferencingRestoreProperty($document, $ref['key'], $results);
1098 /* ActiveMongo Reference FTW! */
1099 $classes[$ref['ref']['class']][] = $ref;
1104 /* {{{ Create needed objects to query MongoDB and replace
1105 * our references by its objects documents.
1107 foreach ($classes as $class => $refs) {
1108 $req = $this->_deferencingCreateObject($class);
1110 /* Load list of IDs */
1112 foreach ($refs as $ref) {
1113 $ids[] = $ref['ref']['$id'];
1116 /* Search to MongoDB once for all IDs found */
1119 if ($req->count() != count($refs)) {
1120 $total = $req->count();
1121 $expected = count($refs);
1122 throw new MongoException("Dereferencing error, MongoDB replied {$total} objects, we expected {$expected}");
1125 /* Replace our references by its objects */
1126 foreach ($refs as $ref) {
1127 $id = $ref['ref']['$id'];
1128 $place = $ref['key'];
1130 while ($req->getID() != $id && $req->next());
1132 assert($req->getID() == $id);
1134 $this->_deferencingRestoreProperty($document, $place, clone $req);
1139 /* Release request, remember we
1146 /* Replace the current document by the new deferenced objects */
1147 foreach ($document as $key => $value) {
1148 $this->$key = $value;
1153 // void getColumnDeference(&$document, $propety, ActiveMongo Obj) {{{
1155 * Prepare a "selector" document to search treaing the property
1156 * as a reference to the given ActiveMongo object.
1159 final function getColumnDeference(&$document, $property, ActiveMongo
$obj)
1161 $document["{$property}.\$id"] = $obj->getID();
1165 // void findReferences(&$document) {{{
1167 * Check if in the current document to insert or update
1168 * exists any references to other ActiveMongo Objects.
1172 final function findReferences(&$document)
1174 if (!is_array($document)) {
1177 foreach($document as &$value) {
1178 $parent_class = __CLASS__
;
1179 if (is_array($value)) {
1180 if (MongoDBRef
::isRef($value)) {
1181 /* If the property we're inspecting is a reference,
1182 * we need to remove the values, restoring the valid
1186 '$ref'=>1, '$id'=>1, '$db'=>1, 'class'=>1, 'dynamic'=>1
1188 foreach (array_keys($value) as $key) {
1189 if (!isset($arr[$key])) {
1190 unset($value[$key]);
1194 $this->findReferences($value);
1196 } else if ($value InstanceOf $parent_class) {
1197 $value = $value->getReference();
1200 /* trick: delete last var. reference */
1205 // void __clone() {{{
1207 * Cloned objects are rarely used, but ActiveMongo
1208 * uses it to create different objects per everyrecord,
1209 * which is used at deferencing. Therefore cloned object
1210 * do not contains the recordset, just the actual document,
1211 * so iterations are not allowed.
1214 final function __clone()
1216 unset($this->_cursor
);
1217 $this->_cloned
= true;
1223 // GET DOCUMENT ID {{{
1227 * Return the current document ID. If there is
1228 * no document it would return false.
1230 * @return object|false
1232 final public function getID()
1234 if ($this->_id
instanceof MongoID
) {
1243 * Return the current key
1247 final function key()
1249 return $this->getID();
1255 // Fancy (and silly) query abstraction {{{
1257 final protected function doQuery()
1259 $col = $this->_getCollection();
1260 if (count($this->_columns
) > 0) {
1261 $cursor = $col->find((array)$this->_query
['query'], $this->_columns
);
1263 $cursor = $col->find((array)$this->_query
['query']);
1265 if (is_array($this->_sort
)) {
1266 $cursor->sort($this->_sort
);
1268 if ($this->_limit
> 0) {
1269 $cursor->limit($this->_limit
);
1271 if ($this->_skip
> 0) {
1272 $this->skip($this->_skip
);
1274 /* Our cursor must be sent to ActiveMongo */
1275 $this->setCursor($cursor);
1278 final function columns($columns)
1280 if (!is_array($columns) && !is_string($columns)) {
1284 if (is_string($columns)) {
1285 $columns = explode(",", $columns);
1288 foreach ($columns as $id => $name) {
1289 $columns[trim($name)] = 1;
1290 unset($columns[$id]);
1293 $this->_columns
= $columns;
1300 final function where($column_str, $value)
1302 $column = explode(" ", $column_str);
1303 if (count($column) != 1 && count($column) != 2) {
1304 throw new ActiveMongo_Exception("Failed while parsing '{$column_str}'");
1305 } else if (count($column) == 2) {
1306 switch ($column[1]) {
1327 throw new ActiveMongo_Exception("Failed to parse '{$column[1]}'");
1329 $value = array($op => $value);
1330 if (is_array($value) ||
$op != '$near') {
1331 throw new ActiveMongo_Exception("Cannot use comparing operations with Array");
1333 } else if (is_array($value)) {
1334 $value = array('$in' => $value);
1337 $this->_query
['query'][$column[0]] = $value;
1340 final function sort($sort_str)
1342 $this->_sort
= array();
1343 foreach ((array)explode(",", $sort_str) as $sort_part_str) {
1344 $sort_part = explode(" ", $sort_part_str, 2);
1345 switch(count($sort_part)) {
1347 $sort_part[1] = 'ASC';
1352 throw new ActiveMongo_Exception("Don't know how to parse {$sort_part_str}");
1355 switch (strtoupper($sort_part[1])) {
1363 throw new ActiveMongo_Exception("Invalid sorting direction {$sort_part[1]}");
1365 $this->_sort
[ $sort_part[0] ] = $sort_part[1];
1369 final function limit($limit=0, $skip=0)
1371 if ($limit < 0 ||
$skip < 0) {
1374 $this->_limit
= $limit;
1375 $this->_skip
= $skip;
1382 require_once dirname(__FILE__
)."/Validators.php";
1389 * vim600: sw=4 ts=4 fdm=marker
1390 * vim<600: sw=4 ts=4