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.

4 comments:

  1. Where to create all the classes that you have mentioned ??? Can u please clarify a bit more...

    ReplyDelete
  2. You can create a "Custom" folder in library and inside Custom folder create another folder called Mango. Place all these file inside Mongo directory. In your application.ini file put autoloadernamespaces[] = "Custom_". Hope this helpes you.

    ReplyDelete
  3. Can you tell how to integrate Mongo with Zend Framework 2.. I have downloaded sample skeleton from http://akrabat.com/zend-framework-2-tutorial/ .(i.e. downloaded PDF)and pasted the above mentioned library inside vendor folder .. Now i am struck..

    ReplyDelete
  4. For zend 2, you have to use php 5.3 native namespace and for that you have to changes the classes name of Mongo library so that it support php namespace.

    ReplyDelete