How to use MongoDB with PHP

Let’s give our database schemas more freedom

Jakub Kapuscik
Level Up Coding
Published in
3 min readApr 10, 2020

--

source: mongodb.com

MongoDB is a great choice for a number of applications. In the PHP world, we can also try something more than just a LAMP stack and give our database schemas more freedom. One of the most popular Object Relational Mappers (ORM) for PHP is the Doctrine that also happens to have a very good implementation of Object Document Mapping (ODM) for MongoDB. We will not go into details about the advantages or disadvantages of NoSql and SQL databases but see how we can build a very simple application if we have already decided to use Mongo.

Complete source code is available in the following repository:

We need to create a shopping cart application with REST API that will allow us to:

  • add a new product to a catalog
  • update name of a product
  • create a new shopping cart
  • add and remove products from a shopping cart
  • record when a product was added to a cart

We also have a set of requirements:

  • price of a product has to be positive and has a specified currency of EUR, PLN or USD
  • we can only have a single product of given type in a basket and no more than 4 product at the same time

We will be using the Symfony framework as it integrates nicely with Doctrine ODM. We can install the library and generate basic configuration by running the following commands:

composer config extra.symfony.allow-contrib truecomposer require doctrine/mongodb-odm-bundle

We will be accessing a database in a similar manner as we would with an ORM in Doctrine. We are using annotations in models that will indicate which class variables should be persisted. In our Product, we are providing name, price, and currency as constructor arguments. There is no much logic required so the class is very straightforward.

--

--