PHP8.1, Enum Classes and Doctrine
One of the new features in PHP8.1 is support for Enum classes. This post is a short intro to how you can use this feature together with Doctrine.
In this article
Support for Enum classes made its way into Doctrine gradually, but since version 2.12.0 it is easy to use Enums in Symfony entities and repositories. Supported are BackedEnums, which hold a string or int value that can be persisted to the database.
Example – defining an enum class
<?php
namespace App\Enum\Advert;
enum EstateType: string
{
case FLAT = 'flat';
case HOUSE = 'house';
}
Example – defining an entity
Defining the estateType property
- In the annotation, the MySQL type has to be
stringorint, depending on the type of the Enum. - You have to add enumType to the annotation, e.g.
enumType=Enum\Advert\EstateType::class - You can define a default value using the Enum.
- Enums can also be used for array-type properties.
Getters and setters
When an Enum is used in the property definition, you no longer need to work with the raw values (string or int), because Doctrine returns the Enum directly.
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Enum;
/**
* @ORM\Table(name="advert")
* @ORM\Entity(repositoryClass="App\Repository\AdvertRepository")
*/
class Advert
{
...
/**
* @ORM\Column(
* name="estate_type",
* type="string",
* enumType=Enum\Advert\EstateType::class,
* length=20,
* nullable=false
* )
*/
private Enum\Advert\EstateType $estateType = Enum\Advert\EstateType::FLAT;
public function setEstateType(Enum\Advert\EstateType $estateType): Advert
{
$this->estateType = $estateType;
return $this;
}
public function getEstateType(): Enum\Advert\EstateType
{
return $this->estateType;
}
...
Repository
You can also work with Enums in the findBy methods of repositories.
$advertRepository = $this->em->getRepository(Entity\Advert::class);
return $advertRepository->findBy(['estateType' => Enum\Advert\EstateType::FLAT]);
They can also be passed as parameter values to the QueryBuilder.
$qb = $this->createQueryBuilder('advert');
$qb
->where('advert.estateType = :estateType')
->setParameter('estateType', Enum\Advert\EstateType::FLAT);