Domain-Driven Design Repositories with Doctrine ORM and ODM in Symfony

Welcome to my first Domain-Driven Design in PHP post.


The following code is inspired by the Domain-Driven Design in PHP book written by Carlos Buenosvinos (@carlosbuenosvinos) and Keyvan Akbary (@keyvanakbary):

Value Objects

My examples code include Value Objects for the identifiers of Aggregate Roots (AR) For now they will be created manually. Later we will see how to use custom Doctrine DBAL types to persist them.


Doctrine Repository



The ODM implementation (e.g. MongoDB) looks very similar:



I recommend to use XML mapping for your Domain Models. This way your class remains POPO and does not mix ”’infrastructure”’ with ”’domain”’ concerns.

Feel free to join the discussion about this topic on GitHub:


Here is an ODM Document example:


For those who still like to use annotations here is an example Entity:




Naming Conventions

Feel free to join the discussion about naming repositories and other best practices on GitHub.


Using PHP YAML Extension and Unicode on Entity column with Doctrine Events

I have a Rails legacy database that uses a YAML formatted array in a column. My new App is based on Symfony2 and Doctrine2.

To make this column useable in Sonata Admin I had to (re-)convert between PHP Array and YAML.


This worked fine using Doctrine Events:


Note the YAML_UTF8_ENCODING constant when emitting. By default yaml_emit uses the YAML_ANY_ENCODING constant.

All constants can be found here:

How to inject Symfony Security into Doctrine Event Listener without Circular Reference Exception

As of Symfony 2.6, you can inject the security.token_storage into your listener. This service will contain the token as used by the SecurityContext in <=2.5.




How to use CHAR instead of VARCHAR with Doctrine ORM