Doctrine Orm - An Introduction and Then a New Idea

What is Doctrine ORM

Doctrine is one of the most popular ORM systems for PHP. It is written as a fully standalone library though is most famously used as the ORM that is bundled with a standard Symfony project.

Read the docs herehere

Doctrine ORM is only one of the projects projects that Doctrine has built, however it does build upon all of the other projects.

What is an ORM

An ORM, or Object Relational Mapper, attempts to allow developers write code and work with objects and then have the persistance and relation of those objects handled behind the scenes, thereby allowing the developer to focus on the domain issues and not in hand crafting a large amount of SQL schema and query logic.

This becomes especially useful as a project progresses and things are added or refactored. The ORM can ultimately allow the developer to focus on the code and then the schema and query logic can be updated as you go, generally with something called database migrations. The benefit of not having to manually refactor large amounts of SQL logic is definitely not to be sniffed at.

Generally when working with Doctrine entities, the code is very much plain vanilla PHP. I prefer to keep the Doctrine entities as basic as possible, purely focussed on data access data access, with any extra logic then being handled in other classes. Again this aids with refactoring and comprehension and sticks more closely to the single responsibility principle single responsibility principle.

Doctrine Metadata

The crux of Doctrine’s work hinges around the management and utlisation of meta data which describes exactly how entities are structured and related to each other and how they should be stored and represented in the database.

There are three main ways people tend to manage this meta data, XML, Yaml and PHP Annotations. They all have their pros and cons, though I think it would be fair to say that the PHP Annotations approach is probably the most popular.

You can read all about the meta data drivers on Doctrines documentation.

New Idea

In addition to the traditional three drivers of XML, Yaml and PHP Annotations there is a Static PHP Driver which is documented here

I think this is a perfect compromise, it keeps things in pure PHP but also in the Entity classes.

To explore this idea I have developed a small repo that utilises this driver and present a possible way it can be used to power a highly trait driven way of composing Doctrine entities.

Rather than repeat myself, I’ll simply link you through to the project Doctrine Static Meta, also available on packagist

Tags: doctrineormphpdatabase