You are browsing a version that has not yet been released. |
:depth: 3
index basic-usage collections-strategy by-value-by-reference laminas-form enum-strategy performance-considerations
Using Enums with PHP 8.1
Doctrine ORM 2.11 introduced support for PHP 8.1 enums. To make use of backed enums with doctrine-laminas-hydrator, you need to set up a hydration strategy.
The Enum and Entity
The following example uses a card with an enum representing hearts, diamonds, clubs or spades:
1 enum Suit: string {
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
#[Entity]
class Card
{
/** ... */
#[Column(type: 'string', enumType: Suit::class)]
public Suit $suit;
public function getSuit(): Suit
{
return $this->suit;
}
public function setSuit(Suit $suit): void
{
$this->suit = $suit;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Custom Hydration Strategy
Next, you need to create a hydration strategy for your backed enum:
1 namespace Application\Hydrator\Strategy;
use Laminas\Hydrator\Strategy\StrategyInterface;
class SuitHydratorStrategy implements StrategyInterface
{
public function extract($value, ?object $object = null): ?int
{
return null === $value ? null : Suit::tryFrom($value)->value;
}
public function hydrate($value, ?array $data): ?Suit
{
return null === $value ? null : Suit::tryFrom($value);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Usage Example
Once you have enum, entity and strategy set up, you can wire it all together by adding the strategy to the relevant field in your hydrator.