PHP Enums with Methods and Interfaces

PHP Enums with Methods and Interfaces

PHP Enums with Methods and Interfaces

A backed enum that implements an interface and provides helper methods.

interface HasLabel
{
    public function label(): string;
}

enum OrderStatus: string implements HasLabel
{
    case Pending   = 'pending';
    case Confirmed = 'confirmed';
    case Shipped   = 'shipped';
    case Cancelled = 'cancelled';

    public function label(): string
    {
        return match($this) {
            self::Pending   => 'Awaiting confirmation',
            self::Confirmed => 'Order confirmed',
            self::Shipped   => 'On its way',
            self::Cancelled => 'Cancelled',
        };
    }

    public function isFinal(): bool
    {
        return in_array($this, [self::Shipped, self::Cancelled]);
    }

    public static function fromLabel(string $label): self
    {
        foreach (self::cases() as $case) {
            if ($case->label() === $label) {
                return $case;
            }
        }
        throw new ValueError("Invalid label: {$label}");
    }
}

// Usage
$status = OrderStatus::Confirmed;
echo $status->label();         // "Order confirmed"
echo $status->value;           // "confirmed"
echo $status->isFinal() ? 'yes' : 'no'; // "no"

$fromDb = OrderStatus::from('shipped'); // OrderStatus::Shipped
All Comments