Using Doctrine Annotations in Sylius | Arroba IT
Skip to content
sylius doctrine

Using Doctrine Annotations in Sylius

Dec 16, 2018

Unclutter your project

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.

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.

1parameters:
2 # Adds a fallback DATABASE_URL if the env var is not set.
3 # This allows you to run cache:warmup even if your
4 # environment variables are not available yet.
5 # You should not need to change this value.
6 env(DATABASE_URL): ''
7 
8doctrine:
9 dbal:
10 driver: 'pdo_mysql'
11 server_version: '%env(resolve:DATABASE_SERVER_VERSION)%'
12 charset: UTF8
13 
14 url: '%env(resolve:DATABASE_URL)%'
15 orm:
16 auto_generate_proxy_classes: '%kernel.debug%'
17 naming_strategy:
18 doctrine.orm.naming_strategy.underscore
19 auto_mapping: true
20 mappings:
21 App:
22 is_bundle: false
23 type: yml
24 dir: '%kernel.project_dir%/src/Resources/config/doctrine'
25 prefix: 'App\Entity'
26 alias: App

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.

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

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:

Screenshot of the described PhpStorm menu.

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

Screenshot of the class annotations generated by PhpStorm

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:

Screenshot of the generated class member annotationsConclusion:

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