An efficient way to treat MongoDB in Symfony.

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need. In addition, it is exceptionally developer friendly. No hassle with table creation, column definitions, data types. The document model maps to the objects in your application code, making data easy to work with.

In Symfony world a mainstream solution to work with it is Doctrine MongoODM library. Unfortunately, it is extremely slow and forces you to maintain model schema which is effectively kills all profit at the grassroots level. This happens mostly because Doctrine has to traverse an object tree to map values to corresponding object properties or in other words hydrate an object. It also has to do an inverse operation to take a storable data.

I was not comfortable with that state of things. So I tried to find a better approach that amplify power of the store. What if we use a data array provided by MongoDB as is, just wrap it a little bit by an object. The hydration and persistence would take no time and be as fast as possible. Effectively it is just about setting or getting an array from an object’s property called values. We always have storable data within reach, no need to traverse anything. On the other hand, a cover object plays a role of a contract adding objectish aspects like data encapsulation, methods\properties visibility, type checks, method definitions, interfaces and so on.

Here’s just a few examples that demonstrates the idea :

So I started developing a solution around the concept, which is later became known as a schema less, fast hydration and persistence document mapper library called makasim/yadm and the bundle makasim/yadm-bundle.

Let’s move to a practical example to see how it all works. For that we have to create a basic project and require the bundle:

$ composer create-project symfony/skeleton acme; cd acme;
$ composer require makasim/yadm-bundle

The model design is a essential starting point so take a look at the imaginary Order model below. It takes a currency, amount, and a number.

The next step is to configure the bundle:

CRUD examples:

I’ve showed just a small portion of awesomeness that comes with the bundle.

There are a lot more so try it in your next Symfony application.

Have fun and give me feedback on occasion!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.