Showing posts with label Mongo library. Show all posts
Showing posts with label Mongo library. Show all posts

Monday, April 4, 2011

Mongodb and Zend Framework using Mongo php library

Here you can use Mongodb(NoSql) database with Zend Framework using Mongo php library. I have created three classes Custom_Mongo_Instance, Custom_Mongo_Db and Custom_Mongo_Collection extending Mongo, MongoDB and MongoCollection respectively. So that you can overrides its methods easily.

First download mongo library for php from here

Step 1 : Custom_Mongo_Instanc

class Custom_Mongo_Instance extends Mongo
{
public function __construct( $server = "mongodb://localhost:27017", $options = array("connect" => TRUE) ) {
parent::__construct($server, $options);
}
}
Step 2 : Custom_Mongo_Db

class Custom_Mongo_Db extends MongoDB
{
public function __construct( Mongo $conn, $name ) {
parent::__construct( $conn, $name );
}
}
Step 3 : Custom_Mongo_Collection

class Custom_Mongo_Collection extends MongoCollection
{
public function __construct ( $name, $db = null ){
if($db == null) $db = Zend_Registry::get('mongoDB');
parent::__construct ( $db , $name );
}

public function insert( array $a, $options = array())
{
$a['created'] = date('Y-m-d H:i');
parent::insert( $a, $options);
}
}

Step 4 : Usage

$cnn = "mongodb://username:password@localhost:27017";
try{
$mongo = new Custom_Mongo_Instance($cnn);
$mongoDB = new Custom_Mongo_Db($mongo, "dbname");
}catch(Exception $e){echo $e->getMessage();exit;}

$collection = new Custom_Mongo_Collection("my_collection", $mongoDB);
$data['first_name'] = "Ritesh";
$data['last_name'] = "jha"
$collection->insert($data);

Thats all. Now you can check the data either using mongo console or some third party GUI admin tools.