Use PHP Enums as Doctrine type in Symfony

Smaine Milianni
2 min readDec 29, 2021
credit: sensiolabs tweet

PHP 8.1 adds support for Enumerations. An Enumeration, is an enumerated type that has a fixed number of possible values. (see more details)

✍🏻 In this article, I’ll show you how to use an Enum as a doctrine WITHOUT adding configuration.

First, what is a doctrine type?

đź“•In short, a doctrine type is a type used to convert a PHP value to a database platform and the inverse. A type should have a class that implements 2 methods convertToDatabaseValue and convertToPHPValue.

Adding a custom type in a Symfony application is easy and very well documented, I tried quickly to implement an enum type and then tweeted my approach, my goal was to have use autoconfiguration to not have to declare each type in configuration.

As I write these lines the Enums type doesn’t exists yet let’s start our journey to implement it with our hands 🙌.

đź’ˇThe hack to bypass the configuration is to autoconfigure a base EnumType and then extend it anytime we need to refer to a new Enum class.

1- Create the Enum

--

--

Smaine Milianni

Fullstack Developer- certified Symfony 4,5 and certified AWS Solution Architect - Freelancer - Remote Worker