Silex and MongoDB simply

Using MongoDB in your Silex Project is quite easy.

I will show this with my Superleansilexplate and will integrate it there as an example.
Since i dont want to integrate MongoDB in Superleansilexplate it will just become an additional gist.

Given you have some smaller amount of data like a counter that needs to be stored or other loose coupled datasets, we simply speak to MongoDB “directly” and store the data via Doctrine MongoDB Abstraction Layer.
Since i presume the Data / Document Structure isnt that complex we dont use Doctrine MongoDB ODM (the Object Document Mapper).
If you want to use it instead, try this Silex Extensions.

So we use this SilexExtensions collection and install it via git:

 cd mysilexproject
 git clone git@github.com:fate/Silex-Extensions.git vendor/silex-extension

Then we install the doctrine mongodb libary manually:

 git clone --recursive https://github.com/doctrine/mongodb vendor/mongodb

The extension collection has some more poviders but you can just ignore them and just focus on the MongoDbExtension.

i actually dont like extensions collections. i would prefer to clone each extensions individually. thou its not much code overhead, but when it comes to the vendor dependencies it can become quite messy IMHO

Alright now the code.
Edit src/app.php and register the namespace for the extension:

 $app['autoloader']->registerNamespace('SilexExtension', __DIR__ . '/../vendor/silex-extension/src');

Then register the MongoDbExtension;

 $app->register(new SilexExtension\MongoDbExtension(), array(
 'mongodb.class_path' => __DIR__ . '/../vendor/mongodb/lib',
 'mongodb.connection' => array(
 'server' => 'mongodb://mysecretuser:mysecretpassw@localhost',
 'options' => array(),
 'eventmanager' => function($eventmanager) {
 }
 )
 ));

and finally query your MongoDB collection of choice and display the resultset as json:

$app->get('/data-from-mongodb', function() use($app) {

$coll = $app['mongodb']->selectDatabase('mydb')->selectCollection('mycoll');
 $query = array(
 'query' => 'value'
 );
 $sort = array(
 'count' => -1,
 );
 $r = $coll->find($query)->sort($sort)->toArray();
 $response = new Response();
 $response->headers->set('Content-type', 'application/json');
 $response->setContent(json_encode($r));
 return $response;
 });

Easy

2 Replies to “Silex and MongoDB simply”

Comments are closed.