PHP enums as a state machine, with a Drupal field
Every shop I have worked on ends up with a status column that three different people treat as a free-text field. One controller sets shiped, a migration writes Paid with a capital letter, and a cron job happily moves a cancelled order back to "paid". I wanted the allowed states and the allowed moves between them to live in exactly one place, checked by the language rather than by convention. A PHP backed enum does that in about thirty lines.
The enum owns the rules
A backed enum gives each case a scalar value you can store in a database, and it can carry methods. That means the transition table can sit right next to the cases it describes:
<?php
declare(strict_types=1);
namespace Drupal\my_shop\Order;
enum OrderStatus: string {
case Draft = 'draft';
case Paid = 'paid';
case Shipped = 'shipped';
case Cancelled = 'cancelled';
public function label(): string {
return match ($this) {
self::Draft => 'Draft',
self::Paid => 'Paid',
self::Shipped => 'Shipped',
self::Cancelled => 'Cancelled',
};
}
/**
* @return list<self>
*/
public function allowedNext(): array {
return match ($this) {
self::Draft => [self::Paid, self::Cancelled],
self::Paid => [self::Shipped, self::Cancelled],
self::Shipped, self::Cancelled => [],
};
}
public function canMoveTo(self $next): bool {
return in_array($next, $this->allowedNext(), TRUE);
}
public function moveTo(self $next): self {
if (!$this->canMoveTo($next)) {
throw new \DomainException(sprintf('Cannot go from %s to %s.', $this->value, $next->value));
}
return $next;
}
/**
* @return array<string, string>
*/
public static function options(): array {
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->label();
}
return $options;
}
}
Two things I like here. match is exhaustive in practice: if I add a Refunded case and forget a branch, PHP throws UnhandledMatchError the first time that case hits the method instead of silently returning nothing. And cases() is generated for me, so options() can never drift out of sync with the enum.
Using it with a Drupal list field
Drupal stores the field as a plain string, so the enum sits at the edges: convert on the way in, convert back to ->value on the way out. tryFrom() returns null for unknown input, while from() throws a ValueError. I use tryFrom() for data I do not control (legacy rows) and from() where bad input is a bug.
use Drupal\my_shop\Order\OrderStatus;
// Reading: tolerate legacy or empty values.
$current = OrderStatus::tryFrom((string) $order->get('field_status')->value)
?? OrderStatus::Draft;
// Writing: this throws a DomainException on an illegal move.
$next = $current->moveTo(OrderStatus::Shipped);
$order->set('field_status', $next->value);
$order->save();
// Form API: the select options come straight from the enum.
$form['status'] = [
'#type' => 'select',
'#title' => t('Status'),
'#options' => OrderStatus::options(),
'#default_value' => $current->value,
];
For the select on an edit form you probably only want to offer legal moves. Build the options from $current->allowedNext() plus the current case, and the UI can no longer offer a transition the model would reject.
Where I would still be careful
Enum cases are objects, so $order->set('field_status', $next) without ->value will not do what you want; always hand Drupal the scalar. Backed enums do serialize to their value with json_encode(), which is handy for REST responses, but the transition rules are not enforced by the database, so a direct SQL update or a migration can still write nonsense. I treat the enum as the gatekeeper for application code and add validation in hook_entity_presave if I need a hard guarantee.
Use this when a field has a small, closed set of values with rules attached. If editors need to add states from the admin UI, a vocabulary or config entity is the better fit; the enum is for states that your code has to reason about.