Mastering PHP 8.1 Enums: From Basics to Advanced Patterns

This article explains how PHP 8.1 enums—both plain and backed—can be used to model task priorities, add type safety, serialize to databases, define custom methods, and integrate with notification senders, demonstrating clean architecture and design benefits for backend applications.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Mastering PHP 8.1 Enums: From Basics to Advanced Patterns

Introduction

Enums (enumerations) are a powerful tool in software development that can improve architecture and design. PHP lacked native enum support for years, but PHP 8.1 finally introduced it, opening many possibilities.

Why Use Enums

An enum is a data type representing a predefined set of constants. For a To‑Do application, an enum can express task priority values instead of using raw strings.

enum Priority {
    case LOW;
    case NORMAL;
    case HIGH;
}

Using the enum as a property type in the Task entity makes the allowed priority values explicit and eliminates guesswork when handling the entity.

final class Task {
    public function __construct(
        public string $title,
        public string $description,
        public Priority $priority,
    ) {}
}

$task = new Task(
    title: 'My First Task',
    description: 'Do something',
    priority: Priority::HIGH,
);

Backed Enums for Persistence

Plain enums are objects, which makes storing them directly in a database cumbersome. PHP also supports backed enums that associate a scalar value (string or int) with each case, enabling easy serialization.

enum Priority: string {
    case LOW = 'low';
    case NORMAL = 'normal';
    case HIGH = 'high';
}

When creating a Task, you can convert a user‑provided string to the enum using Priority::from($value):

$task = new Task(
    title: 'My First Task',
    description: 'Do something',
    priority: Priority::from($priority),
);

Enum Methods

Enums can contain methods just like regular classes. Combining a method with the match expression enables expressive logic. For example, assigning a color to each priority:

enum Priority: string {
    case LOW = 'low';
    case NORMAL = 'normal';
    case HIGH = 'high';

    public function color(): string {
        return match ($this) {
            self::LOW => 'green',
            self::NORMAL => 'blue',
            self::HIGH => 'red',
        };
    }
}

$task->priority->color(); // returns 'red'

Extending Enum Methods for Notifications

Beyond simple helpers, enums can coordinate more complex behavior. Suppose each priority should trigger a different notification channel. First, define a contract:

interface NotificationSender {
    public function send(Task $task): void;
}

Implement concrete senders (code omitted for brevity): EmailSender, SlackSender, and PhoneMessageSender, each implementing NotificationSender.

final class EmailSender implements NotificationSender {
    public function send(Task $task): void { /* email logic */ }
}

final class SlackSender implements NotificationSender {
    public function send(Task $task): void { /* slack logic */ }
}

final class PhoneMessageSender implements NotificationSender {
    public function send(Task $task): void { /* sms logic */ }
}

Add a method to the enum that returns the appropriate sender based on the priority:

enum Priority: string {
    case LOW = 'low';
    case NORMAL = 'normal';
    case HIGH = 'high';

    public function notificationSender(): NotificationSender {
        return match ($this) {
            self::LOW => new EmailSender(),
            self::NORMAL => new SlackSender(),
            self::HIGH => new PhoneMessageSender(),
        };
    }
}

Now creating a task and sending the correct notification becomes straightforward:

$task = new Task(
    title: 'My First Task',
    description: 'Do something',
    priority: Priority::HIGH,
);

$task->priority->notificationSender()->send($task);

Conclusion

Enums provide limitless possibilities for improving applications when used wisely. They enable cleaner, more maintainable codebases and can serve as core building blocks for architecture and design, handling everything from simple value mapping to sophisticated behavior such as notification routing.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPbackend-developmentEnumsphp-8.1backed-enumsdesign-patterns
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.