Symfony: How to add table prefixes with Doctrine

KC Müller
2 min readFeb 21, 2020

--

Sometimes, especially when your application grows huge, you want to add a prefix to your database tables to group them according to their domain. This can be done automatically using an Event Listener.

Let’s say you want to add a calendar component to your application, having entities named “configuration”, “appointment” and “detail”. You would create the entities using these names as table names, but the event listener would automatically add the “calendar” prefix in front, resulting in “calendar_configuration”, “calendar_appointment” and “calendar_detail” which improves the readability of your database structure but wouldn’t add additional complexity or naming conventions when writing your code. Other use cases would be multiple applications sharing a single database — in this case every application could have its own prefix.

In this example I will add an Event Listener that will automatically add the current bundle from the entity class name as a table prefix if this wasn’t already done in the table name definition.

Step1: Add your Event Listener

The base of this Event Listener can be found here: https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/cookbook/sql-table-prefixes.html
I adjusted it to create the prefix from the entity class name. The setConfig() method and the $config property are used to add a configuration from the parameters and are optional.

In this case, the Event Listener is placed in the /EventListener Folder in my application.

TablePrefixEventListener.php

Step2: Add your configuration

In my case I added a configuration file to map the bundle namespace to a table prefix. This could also be done code wise, the configuration just makes it more flexible. The configuration file is optional.

The configuration file would live in your /config/packages folder.

table_prefix.yaml

# mapping from bundle name to table prefix
parameters:
table_prefix:
calendar: calendar_
foo: bar_

Step3: Registering the Event Listener

You will register the Event Listener in your /config/services.yaml file as shown below. If you don’t want to use a config file, you would just remove the lines of the “calls” section.

services.yaml

services:
kernel.listener.prefix:
class: App\EventListener\TablePrefixEventListener
# Adding the table_prefix configuration
calls:
- [ setConfig, [ '%table_prefix%' ] ]
tags:
- { name: doctrine.event_listener, event: loadClassMetadata, method: loadClassMetadata }

Now everytime an entity is created or loaded, the prefix will be automatically applied to the table name. If you are adding this to an existing database schema be sure to drop it and regenerate it to apply the changes.

--

--