Before we start using MongoDB in our project, we have to setup a connection details, by adding them to app/config/config.php
file:
//...
'mongo' => [
'dbname' => 'test'
],
//...
To make MongoDB available in the application, you have to create a service provider
use Phalcon\DiInterface;
use Vegas\DI\ServiceProviderInterface;
use Phalcon\Mvc\Url as UrlResolver;
class MongoServiceProvider implements ServiceProviderInterface
{
const SERVICE_NAME = 'mongo';
/**
* {@inheritdoc}
*/
public function register(DiInterface $di)
{
$di->set(self::SERVICE_NAME, function() use ($di) {
$mongo = new \MongoClient();
return $mongo->selectDb($di->get('config')->mongo->db);
}, true);
}
/**
* {@inheritdoc}
*/
public function getDependencies()
{
return [
CollectionManagerServiceProvider::SERVICE_NAME
];
}
}
use Phalcon\DiInterface;
use Vegas\DI\ServiceProviderInterface;
use Phalcon\Mvc\Url as UrlResolver;
class CollectionManagerServiceProvider implements ServiceProviderInterface
{
const SERVICE_NAME = 'collectionManager';
/**
* {@inheritdoc}
*/
public function register(DiInterface $di)
{
$di->set(self::SERVICE_NAME, function() use ($di) {
return new \Phalcon\Mvc\Collection\Manager();
}, true);
}
/**
* {@inheritdoc}
*/
public function getDependencies()
{
return [];
}
}
Once we have a MongoDB setup in application, we can start creating a data-models.
Create a file Foo.php in the models directory in one module.
namespace Foo\Models;
use Vegas\Db\Decorator\CollectionAbstract;
class Fo extends CollectionAbstract
{
/**
* Returns the name of Mongo collection
*/
public function getSource()
{
return 'foo_collection';
}
}