Skip to content
This repository was archived by the owner on Jun 29, 2024. It is now read-only.

Mongo_Collection

colinmollenhour edited this page Sep 13, 2010 · 3 revisions

This class is meant to work in close harmony with Mongo_Document but generally handle things at a collection level. While you could instantiate only the most basic version:

class Model_Post_Collection extends Mongo_Collection {
    public $name = 'posts';
}

and then lump all of your code into the corresponding Mongo_Document class, using this additional level of organization can help keep your document models free from lots of query code. E.g.:

class Model_Post_Collection extends Mongo_Collection {
  public $name = 'posts';
  public function get_most_recent($limit, $offset)
  {
    return $this
      ->find('status', 'published')
      ->sort_desc('created_at')
      ->limit($limit)
      ->offset($offset);
  }
}
// Get Bilbo's 10 latest posts
$posts = Mongo_Collection::factory('post')->find('username','bilbo')->get_most_recent(10,0);
// or if $user is the Model_Post instance:
$posts = $user->collection()->find('id',$user->id)->get_most_recent(10,0);
$posts->find(array('tags' => 'adventure')); // filter by tag
echo $posts->count(); // get a count, only now is the cursor instantiated and the query executed

The collection instance allows query results to be accessed as an iterator of models rather than arrays:

foreach($posts as $post) {
  echo "{$post->title}\n";
}
Clone this wiki locally