Using custom types in Symfony & Doctrine

ORMs are great. In theory, they insure you against potential changes in your RDBMS and offer an easy plug’n’play solution for integration your domain code with database.

In practice, however, since ORMs have to be compatible with all major vendors, their possibilities are often limited. Perks and tricks of specific RDBMS are left out.

One of such perks is so-called range types in PostgreSQL. There are plenty of cases when range types are applicable, but people (in my experience) often stick to old solution with two separate DATETIME columns.

Last time I asked a fellow developer about the reason behind it and they said: ‘I use Doctrine in my project, and Doctrine does not support it’.

So here we are.

Well, let’s get to coding.

Prerequisites

You’ll need to know about range types in PostgreSQL and be familiar with Symfony and Doctrine.

Apart from that, we’ll be using an awesome lib by the PHP league, Period.

Doctrine Types

You can find the description of how to create a custom type here.

Doctrine type is a class, extending the basic Type class, that describes PHP — Database transformations.

Here we transform the Period object into a daterange string and parse it back into original object.

Symfony Integration

This one is pretty simple, just add your type to configuration:

How to use

First, create an entity that holds a field of the desired type.

Then, write the client code.

Finally, run it!

All the code can be found here.

While I used daterange type as an example here, you can adapt this code to other types too. For example, geoapplications would benefit from incorporating geometric types into their code, while others could take advantage of the XML type.

What is important here is that given that you are not going to change your database in the near future, you could use vendor-specific features by creating your own custom types.

--

--