MongoRecord is a PHP Mongo ORM layer built on top of the PHP Mongo PECL extension
MongoRecord is an extraction from online classifieds site Oodle. Oodle’s requirements for a manageable, easy to understand interface for dealing with the super-scalable Mongo datastore was the primary reason for MongoRecord. It was developed to use with PHP applications looking to add Mongo’s scaling capabilities while dealing with a nice abstraction layer.
- Collection names by convention
- Attributes by convention
- Validations
- Callbacks
- PHP 5.3+
- Mongo PECL
Extract the source files into a directory in your PHP library path.
Using MongoRecord is as simple as declaring classes that are extensions of the base ORM class.
class Person extends BaseMongoRecord
{
}
// initialize connection and database name BaseMongoRecord::$connection = new Mongo(); BaseMongoRecord::$database = 'myapp';
This gives Person basic CRUD methods: save(), destroy(), findOne(), and find().
Every class automatically gets mapped to a Mongo collection by convention.
E.g.
Person → people
MyClass → my_classes
New records can be created by instantiating and saving:
$person = new Person(); $person->save(); // true or false depending on success
$person = Person::findOne(); $person->destroy();
Attributes can be set in bulk on the constructor, one-by-one, or chained.
$person = new Person(array('name' => 'Bob', 'description' => 'foobar'));
$person->setAge(25)->setGender("Male");
$person->save(); // returns true or false
Person::find(array('name' => 'Bob', 'gender' => 'Male')); // finds all male Bobs in the people collection.
Validations can be added based on the name of the attribute
class Person extends BaseMongoRecord
{
public function validatesName($name)
{
if ($name == 'Bob')
return false;
else
return true;
}
}
$person = new Person();
$person->setName("Bob");
$person->save(); // fails!
Callbacks can be added for the following events:
- beforeSave()
- afterSave()
- beforeValidation()
- afterValidation()
- beforeDestroy()
- afterNew()
In a new, save, destroy cycle, the validations are called in the following order:
afterNew -> beforeValidation -> afterValidation -> beforeSave -> afterSave -> beforeDestroy
class Person extends BaseMongoRecord
{
public function beforeSave()
{
if ($this->getName() == 'Bob')
$this->setName('Bill');
}
}