Monday, July 7, 2014

MongoDB and Phalcon PHP - CollectionManager Not Found

MongoDB is supported out of box in Phalcon PHP. Phalcon PHP has very simple yet limited Object-Document Mapper (ODM) library which is used for connecting to NoSQL databases like MongoDB.

To connect to MongoDB in Phalcon, a service must be added in DI container as follows:

$di->set('mongo', function() {
    $mongo = new MongoClient();
    return $mongo->selectDB("db_name"); //database name in MongoDB
}, true);

When executing the script related to MongoDB interactions in PhalconPHP, below error is thrown:
Service 'collectionManager' was not found in the dependency injection container

As each MongoDB document is a collection in Phalcon, a collection manager service is needed for initialization of models, keeping record of relations between the different models of the application etc.
To resolve this error, collectionManager service must also be added to DI container.
$di->set('collectionManager', function(){
    return new Phalcon\Mvc\Collection\Manager();
}, true);

So, while working with MongoDB in PhalconPHP, make sure that both mongo and collectionManager services are added to DI container.