Using Doctrine Annotations in Sylius

Unclutter your project

Under the hood Sylius uses Doctrine ORM to map your models to the database. Doctrine offers three ways to define the mapping configuration:

  • Yaml
  • XML
  • Annotations

A fresh Sylius project will use *.yaml files by default, which are living in Resources/config/doctrine/. This is configured in config/packages/doctrine.yml at the very bottom.

Its easy to switch to XML format by changing the yml to xml. Of course you have to migrate any existing *.orm.yml to *.orm.xml. As a newbie to Sylius and Symfony, the many configuration files are overwhelmed me, so I decided to reduce them by doing the database mappings inside my models using Doctrine Annotations. Since Sylius recommends the usage of YAML or XML (for reasons I don’t know), there is no documentation available about how to switch to annotations. However, after some trial and error I got it to work.

type: annotation
dir: '%kernel.project_dir%/src/Entity'

There are only two changes in this file:

  • use annotation as type
  • change the path from the folder with the config files to the folder with your entities / models.

As a last step I had to add the annotations to all my models. This is surprisingly easy with PhpStorm and the Symfony Plugin enabled. With the cursor inside the class I had to type Ctrl + Enter to get this menu:

With selecting the ORM Class item, PhpStorm added the necessary annotations to the class:

In this case the database name is correct as PhpStorm just derives the name from the model. I had to change it to sylius_product. With the menu item ORM Annotation PhpStorm helps you to generate the mapping configurations to the class properties:


I like this approach much better than have the mapping somewhere else hidden.