Use PHP Enums as Doctrine type in Symfony
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.