Skip to content

mhobesong/PHP-MongoDB-ORM

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple-PHP-MongoDB-ORM

A simple PHP ORM wrapper for MongoDB.

SetUp

require('src/MongoDB_ORM.php');

//set DB credentials
MongoDB_ORM::$_DB_HOST      = "localhost";
MongoDB_ORM::$_DB_USER      = "root";
MongoDB_ORM::$_DB_DATABASE  = "test";
MongoDB_ORM::$_DB_PASSWORD  = "1234";
MongoDB_ORM::$_DB_PORT      = 27017;

Usage

Say we have a Book class defined as follows. You have to specify the collection to which the class will link to as a protected class property with name $_collection. This way, every query is done against the specified collection.

class Book extends MongoDB_ORM
{
	protected $_collection = 'books';
	/**
	* @var string
	*/
	var $title;
	/**
	* @var string[]
	*/
	var $authors;
	/**
	* Price in USD
	* @var int
	*/
	var $price;
}

Insert

$book = new Book();
$author = 'John Wayne';
$title = 'Solid Liquids';
$book->authors = [$author];
$book->title = $title;
$book->save();

Find first occurence

Returns NULL if the document is not found.

$book = new Book();
$document = $book->first(['title' => 'Solid Liquids']);

You can also directly load the instance.

$book = new Book();
$author = 'John Wayne';
$title = 'Solid Liquids';
$book->authors = [$author];
$book->title = $title;
$book->save();

$book2 = new Book(['authors'=>['John Wayne']]);
echo $book2->authors[0]; //"John Wayne";
echo $book2->title; //"Solid Liquids"

Find

Returns an array of objects or an empty array if no match is found.

$book = new Book();
$documents = $book->find(['authors' => [$author]]);

Select all documents

$book = new Book();
$documents = $book->find();

You can specify pipeline stage options as second parameter.

$book = new Book();
$options = ['limit' => 2, 'sort' => ['_id' => -1]];
$documents = $book->find(['authors' => [$author]], $options);

Update

Instance update

$book = new Book();
$book->authors = ['Tim Bakley', 'Rose Javan', 'Mike Andrew'];
$book->title = 'No Way';
$id = $book->save();

$new_title = 'Many Ways';
$book->title = $new_title;
$book->save(); //Updates this instance only

Update all match

$book = new Book();
$filter = ['_id'=>$id];
$set = ['authors'=>['Moses', 'Besong']];

$document = $book->update($filter, $set);

Delete

$book = new Book();
$filter = ['title' => 'No Way'];
$book->delete($filter);

Delete all documents in the collection

$book = new Book();
$book->delete();

Count

Count all document with 'No Way' as 'title'.

$book = new Book();
$filter = ['title' => 'No Way'];
$count = $book->count($filter);

Count all documents in the collection

$book = new Book();
$count = $book->count();

About

A simple PHP ORM wrapper for MongoDB

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages