Class: MongoModel

A class you can extend to create model objects in your application that write to a MongoDB collection in the back-end. Assumes collection and class name are identical, but that the collection is lowercase. Assumes primary key field is named '_id'. The collection can be changed by specifying a custom name property. Note that this class doesn't impose field names. It provides an easy way to get at MongoDB collections using the same pattern as regular SQL-based Model objects, and can be extended to encapsulate your logic around that data.

Usage:

<?php

class MyTable extends MongoModel {
    function get_all_by_x () {
        return MyTable::query ()
            ->order ('x desc')
            ->fetch ();
    }
}

$one = new MyTable (array (
    'fieldname' => 'Some value'
));
$one->put ();
echo $one->keyval ();

$two = MyTable::get ($one->keyval ());

$two->fieldname = 'Some other value';
$two->put ();

$res = MyTable::query ()
    ->where ('fieldname', 'Some other value')
    ->where ('age', array ('$gt' => 123))
    ->order ('fieldname asc')
    ->fetch (10, 5); // limit, offset

$res = MyTable::get_all_by_x ();

foreach ($res as $row) {
    $row->remove ();
}

?>

Also supports validation of values via:

<?php

class MyTable extends MongoModel {
    var $verify = array (
        'email' => array (
            'email' => 1,
            'contains' => '@ourdomain.com'
        ),
        'name' => array (
            'not empty' => 1
        )
    );
}

?>

Or specified as an INI file:

<?php

class MyTable extends MongoModel {
    var $verify = 'apps/myapp/forms/myrules.php';
}

?>

See Form::verify_values for more info on validation rules and file formats.

Differences from Model objects:

  • keyval() method for retrieving the unique ID value and ensuring it's not a MongoId object.

Properties

public $db

The Mongo database (a MongoDB object). Set in the constructor via MongoManager::get_database ();

public $name = ''

The name of the collection to operate on.

public $collection

The Mongo collection (a MongoCollection object).

public $key = '_id'

The primary key field name.

public $keyval = false

The primary key value of the current object.

public $data = array ()

The properties of the current object are stored in this array.

public $fields = array ()

Settings about fields such as relations to other tables.

public $error = false

The error message if an error occurred, or false if there was no error.

public $is_new = false

Keeps track of whether the current object is new and needs to be inserted or updated on save.

public $query_fields = '*'

Fields to return for the current query.

public $query_order = array ()

The order by clause for the current query.

public $query_filters = array ()

A list of where clauses for the current query.

public $verify = array ()

A list of validation rules to apply to ensure data is valid on save.

public $failed = array ()

A list of fields that failed validation on the last put() call.

Methods

public __construct ($vals = false, $is_new = true)

If $vals is false, we're creating a new object from scratch. If it contains an array, it's a new object from an array. If $is_new is false, then the array is an existing field (mainly used internally by fetch()). If $vals contains a single value, the object is retrieved from the database.

public set_database ($conn)

Allows you to inject the database connection into $db. Also sets $collection.

public __call ($name, $arguments)

Custom caller to handle references to related models.

public __get ($key)

Custom getter that uses $this->data array.

public __set ($key, $val)

Custom setter that saves to $this->data array.

public _id ($id = false)

Returns a MongoId object from a regular ID value or if it's already a MongoId value, the original is returned.

public keyval ($id = false)

Returns the ID value from a MongoId object, or the original value if it's not a MongoId object.

public put ()

Save the object to the database. If $verify is set, it will validate the data against any rules in the array, or in the specified INI file if $verify is a string matching a file name.

public remove ($id = false)

Delete the specified or the current element if no id is specified.

public static get ($id)

Get a single object and update the current instance with that data.

public static query ($fields = false)

Begin a new query. Resets the internal state for a new query. Optionally you can pass the fields you want to return in the query, so you can optimize and not return them all.

public order ($order)

Order the query by the specified clauses. Specify each as:

field1 asc, field2 desc

public group ($keys, $initial, $reduce, $options)

Group the query by the specific clauses and immediately return the results as a data structure. The group() function in MongoDB works much differently than GROUP BY in SQL databases. For more info, see:

http://www.php.net/manual/en/mongocollection.group.php

Unlike the group() method in SQL-based models, this method returns the results immediately. For example:

Data structure:

{ category: 1, name: "John" }
{ category: 1, name: "Steve" }
{ category: 2, name: "Adam" }

Query:

<?php

$res = MyModel::query ()->group (
    array ('category' => 1),                               // keys
    array ('items' => array ()),                           // initial
    'function (obj, prev) { prev.items.push (obj.name); }' // reduce
);

?>

Results:

{
  retval: [
    {
      category: 1,
      items: [
        name: "John",
        name: "Steve"
      ]
    },
    {
      category: 2,
      items: [
        name: "Adam"
      ]
    }
  ],
  count: 3,
  keys: 2,
  ok: 1
}

public where ($key, $val)

Add a where condition to the query. This is a field/value combo, and special values are allowed, such as:

->where ('age' => array ('$gt', 18))

public fetch ($limit = false, $offset = 0)

Fetch as an array of model objects.

public single ()

Fetch a single result as a model object.

public count ($limit = false, $offset = 0)

Fetch the number of results for a query.

public fetch_orig ($limit = false, $offset = 0)

Fetch as an array of the original objects as returned from the database.

public fetch_assoc ($key, $value, $limit = false, $offset = 0)

Fetch as an associative array of the specified key/value fields.

public fetch_field ($value, $limit = false, $offset = 0)

Fetch as an array of the specified field name.

public orig ()

Return the original data as an object.