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 +---------------------------------------------------------------------------------+
39 // Class FilterException {{{
43 * This is Exception is thrown if any validation
44 * fails when save() is called.
47 final class FilterException
extends Exception
52 // array get_object_vars_ex(stdobj $obj) {{{
54 * Simple hack to avoid get private and protected variables
60 function get_object_vars_ex($obj)
62 return get_object_vars($obj);
69 * Simple ActiveRecord pattern built on top of MongoDB. This class
70 * aims to provide easy iteration, data validation before update,
71 * and efficient update.
73 * @author César D. Rodas <crodas@php.net>
74 * @license PHP License
75 * @package ActiveMongo
79 abstract class ActiveMongo
implements Iterator
88 private static $_collections;
90 * Current connection to MongoDB
92 * @type MongoConnection
94 private static $_conn;
106 private static $_host;
112 private $_current = array();
118 private $_cursor = null;
120 * Current document ID
127 // string getCollectionName() {{{
129 * Get Collection Name, by default the class name,
130 * but you it can be override at the class itself to give
133 * @return string Colleciton Name
135 protected function getCollectionName()
137 return strtolower(get_class($this));
141 // void install() {{{
145 * This static method iterate over the classes lists,
146 * and execute the setup() method on every ActiveMongo
147 * subclass. You should do this just once.
150 final public static function install()
152 $classes = array_reverse(get_declared_classes());
153 foreach ($classes as $class)
155 if ($class == __CLASS__
) {
158 if (is_subclass_of($class, __CLASS__
)) {
166 // void connection($db, $host) {{{
170 * This method setup parameters to connect to a MongoDB
171 * database. The connection is done when it is needed.
173 * @param string $db Database name
174 * @param string $host Host to connect
178 final public static function connect($db, $host='localhost')
180 self
::$_host = $host;
185 // MongoConnection _getConnection() {{{
189 * Get a valid database connection
191 * @return MongoConnection
193 final protected static function _getConnection()
195 if (is_null(self
::$_conn)) {
196 self
::$_conn = new Mongo(self
::$_host);
198 return self
::$_conn->selectDB(self
::$_db);
202 // MongoCollection _getCollection() {{{
206 * Get a collection connection.
208 * @return MongoCollection
210 final protected function _getCollection()
212 $colName = $this->getCollectionName();
213 return self
::_getConnection()->selectCollection($colName);
217 // bool getCurrentSubDocument(array &$document, string $parent_key, array $values, array $past_values) {{{
219 * Generate Sub-document
221 * This method build the difference between the current sub-document,
222 * and the origin one. If there is no difference, it would do nothing,
223 * otherwise it would build a document containing the differences.
225 * @param array &$document Document target
226 * @param string $parent_key Parent key name
227 * @param array $values Current values
228 * @param array $past_values Original values
232 function getCurrentSubDocument(&$document, $parent_key, Array $values, Array $past_values)
235 * The current property is a embedded-document,
236 * now we're looking for differences with the
237 * previous value (because we're on an update).
239 * It behaves exactly as getCurrentDocument,
240 * but this is simples (it doesn't support
243 foreach ($values as $key => $value) {
244 $super_key = "{$parent_key}.{$key}";
245 if (is_array($value)) {
247 * Inner document detected
249 if (!isset($past_values[$key]) ||
!is_array($past_values[$key])) {
251 * We're lucky, it is a new sub-document,
254 $document['$set'][$super_key] = $value;
257 * This is a document like this, we need
258 * to find out the differences to avoid
261 if (!$this->getCurrentSubDocument($document, $super_key, $value, $past_values[$key])) {
267 if (!isset($past_values[$key]) ||
$past_values[$key] != $value) {
268 $document['$set'][$super_key] = $value;
272 foreach (array_diff(array_keys($past_values), array_keys($values)) as $key) {
273 $super_key = "{$parent_key}.{$key}";
274 $document['$unset'][$super_key] = 1;
281 // array getCurrentDocument(bool $update) {{{
283 * Get Current Document
285 * Based on this object properties a new document (Array)
286 * is returned. If we're modifying an document, just the modified
287 * properties are included in this document, which uses $set,
288 * $unset, $pushAll and $pullAll.
291 * @param bool $update
295 final protected function getCurrentDocument($update=false, $current=false)
298 $object = get_object_vars_ex($this);
301 $current = (array)$this->_current
;
304 foreach ($object as $key => $value) {
309 if (is_array($value) && isset($current[$key])) {
311 * If the Field to update is an array, it has a different
312 * behaviour other than $set and $unset. Fist, we need
313 * need to check if it is an array or document, because
314 * they can't be mixed.
317 if (!is_array($current[$key])) {
319 * We're lucky, the field wasn't
320 * an array previously.
322 $this->_call_filter($key, $value, $current[$key]);
323 $document['$set'][$key] = $value;
327 if (!$this->getCurrentSubDocument($document, $key, $value, $current[$key])) {
328 throw new Exception("{$key}: Array and documents are not compatible");
330 } else if(!isset($current[$key]) ||
$value !== $current[$key]) {
332 * It is 'linear' field that has changed, or
335 $past_value = isset($current[$key]) ?
$current[$key] : null;
336 $this->_call_filter($key, $value, $past_value);
337 $document['$set'][$key] = $value;
341 * It is a document insertation, so we
342 * create the document.
344 $this->_call_filter($key, $value, null);
345 $document[$key] = $value;
349 /* Updated behaves in a diff. way */
351 foreach (array_diff(array_keys($this->_current
), array_keys($object)) as $property) {
352 if ($property == '_id') {
355 $document['$unset'][$property] = 1;
359 if (count($document) == 0) {
366 // void _call_filter(string $key, mixed &$value, mixed $past_value) {{{
370 * This method check if the current document property has
371 * a filter method, if so, call it.
373 * If the filter returns false, throw an Exception.
377 private function _call_filter($key, &$value, $past_value)
379 $filter = array($this, "{$key}_filter");
380 if (is_callable($filter)) {
381 $filter = call_user_func_array($filter, array(&$value, $past_value));
382 if ($filter===false) {
383 throw new FilterException("{$key} filter failed");
385 $this->$key = $value;
390 // void setCursor(MongoCursor $obj) {{{
394 * This method receive a MongoCursor and make
397 * @param MongoCursor $obj
401 final protected function setCursor(MongoCursor
$obj)
403 $this->_cursor
= $obj;
404 $this->setResult($obj->getNext());
410 * Reset our Object, delete the current cursor if any, and reset
415 final function reset()
418 $this->_cursor
= null;
419 $this->setResult(array());
423 // void setResult(Array $obj) {{{
427 * This method takes an document and copy it
428 * as properties in this object.
434 final protected function setResult($obj)
436 /* Unsetting previous results, if any */
437 foreach (array_keys((array)$this->_current
) as $key) {
441 /* Add our current resultset as our object's property */
442 foreach ((array)$obj as $key => $value) {
443 if ($key[0] == '$') {
446 $this->$key = $value;
449 /* Save our record */
450 $this->_current
= $obj;
454 // this find([$_id]) {{{
458 * Really simple find, which uses this object properties
461 * @return object this
463 function find(MongoID
$_id = null)
465 $vars = $this->getCurrentDocument();
469 $res = $this->_getCollection()->find($vars);
470 $this->setCursor($res);
475 // void save(bool $async) {{{
479 * This method save the current document in MongoDB. If
480 * we're modifying a document, a update is performed, otherwise
481 * the document is inserted.
483 * On updates, special operations such as $set, $pushAll, $pullAll
484 * and $unset in order to perform efficient updates
490 final function save($async=true)
492 $update = isset($this->_id
) && $this->_id
InstanceOf MongoID
;
493 $conn = $this->_getCollection();
494 $obj = $this->getCurrentDocument($update);
495 if (count($obj) == 0) {
496 return; /*nothing to do */
499 $this->pre_save($update ?
'update' : 'create', $obj);
501 $conn->update(array('_id' => $this->_id
), $obj);
502 foreach ($obj as $key => $value) {
503 if ($key[0] == '$') {
506 $this->_current
[$key] = $value;
510 $conn->insert($obj, $async);
511 $this->_id
= $obj['_id'];
512 $this->_current
= $obj;
520 * Delete the current document
524 final function delete()
526 if ($this->valid()) {
527 return $this->_getCollection()->remove(array('_id' => $this->_id
));
535 * Delete the current colleciton and all its documents
539 final function drop()
541 $this->_getCollection()->drop();
542 $this->setResult(array());
543 $this->_cursor
= null;
549 * Return the number of documents in the actual request. If
550 * we're not in a request, it will return 0.
554 final function count()
556 if ($this->valid()) {
557 return $this->_cursor
->count();
567 * Return if we're on an iteration and if it is still valid
571 final function valid()
573 return $this->_cursor
InstanceOf MongoCursor
&& $this->_cursor
->valid();
579 * Move to the next document
583 final function next()
585 return $this->_cursor
->next();
589 // this current() {{{
591 * Return the current object, and load the current document
592 * as this object property
596 final function current()
598 $this->setResult($this->_cursor
->current());
605 * Go to the first document
607 final function rewind()
609 return $this->_cursor
->rewind();
615 * Return the current document ID. If there is
616 * no document it would return false.
618 * @return object|false
620 final public function getID()
622 if ($this->_id
instanceof MongoID
) {
631 * Return the current key
637 return $this->getID();
641 // void pre_save($action, & $document) {{{
645 * This method is fired just before an insert or updated. The document
646 * is passed by reference, so it can be modified. Also if for instance
647 * one property is missing an Exception could be thrown to avoid
651 * @param string $action Update or Create
652 * @param array &$document Document that will be sent to MongoDB.
656 protected function pre_save($action, Array &$document)
661 // void on_save() {{{
665 * This method is fired right after an insert is performed.
669 protected function on_save()
674 // void on_update() {{{
678 * This method is fired right after an update is performed.
682 protected function on_update()
687 // void on_iterate() {{{
691 * This method is fired right after a new document is loaded
692 * from the recorset, it could be useful to load references to other
697 protected function on_iterate()
704 * This method should contain all the indexes, and shard keys
705 * needed by the current collection. This try to make
706 * installation on development environments easier.
720 * vim600: sw=4 ts=4 fdm=marker