Order processing looks simple until business rules begin to accumulate. A new order can be paid, shipped, cancelled, or refunded, but not every transition should be possible from every state. If those rules are represented by arbitrary strings scattered throughout an application, inconsistencies become increasingly likely.

PHP’s backed enums provide a useful way to make these states explicit. Available since PHP 8.1, enums are not merely a replacement for constants. They can also hold behavior, allowing a business rule to live close to the states it governs.

In this tutorial, we will model an order workflow using PHP 8.2 or later. The example is deliberately independent of any framework and focuses on domain behavior rather than database infrastructure.

Why Strings Become a Problem

Consider an order table with a status column containing values such as pending, paid, shipped, and cancelled. A developer might compare those values directly in controllers, background jobs, and administrative tools.

Nothing prevents a typo such as “shiped” from entering application logic. More importantly, nothing ensures that all parts of the application agree about which transitions are permitted.

A backed enum establishes a closed set of named states while preserving scalar values suitable for database storage.

Define the Order States

<?php

declare(strict_types=1);

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';
    case Cancelled = 'cancelled';
    case Refunded = 'refunded';
}

The names are PHP enum cases. The associated strings are their persisted representations. Keeping those concepts separate allows developers to work with OrderStatus::Paid rather than repeating the string “paid” throughout the codebase.

Put Transition Rules in One Place

Enums can define methods. We can use that capability to describe the valid next states of an order.

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';
    case Cancelled = 'cancelled';
    case Refunded = 'refunded';

    /** @return list<self> */
    public function allowedNext(): array
    {
        return match ($this) {
            self::Pending => [
                self::Paid,
                self::Cancelled,
            ],
            self::Paid => [
                self::Shipped,
                self::Refunded,
            ],
            self::Shipped => [
                self::Refunded,
            ],
            self::Cancelled,
            self::Refunded => [],
        };
    }

    public function canTransitionTo(self $next): bool
    {
        return in_array(
            $next,
            $this->allowedNext(),
            true
        );
    }
}

This second declaration replaces the first in the runnable example; do not include both definitions in the same PHP file.

The transition table is intentionally simplified. A real commerce application might distinguish payment authorization from capture, shipment from delivery, and full refunds from partial refunds. Those decisions belong to the business domain, not to the enum mechanism itself.

Build an Order That Enforces the Rules

The Order object can now require a valid status transition before changing its state.

final class Order
{
    public function __construct(
        public readonly int $id,
        private OrderStatus $status = OrderStatus::Pending
    ) {
    }

    public function status(): OrderStatus
    {
        return $this->status;
    }

    public function transitionTo(OrderStatus $next): void
    {
        if (!$this->status->canTransitionTo($next)) {
            throw new DomainException(sprintf(
                'Cannot move order %d from %s to %s',
                $this->id,
                $this->status->value,
                $next->value
            ));
        }

        $this->status = $next;
    }
}

$order = new Order(42);

$order->transitionTo(OrderStatus::Paid);
$order->transitionTo(OrderStatus::Shipped);

echo $order->status()->value, PHP_EOL;

The expected output is “shipped”. Attempting to cancel the order after shipment raises a DomainException because that transition is absent from the permitted list.

Notice that the object does not expose a public writable status property. If callers could assign a new state directly, they could bypass the transition policy entirely.

Persisting Enums Without Losing Type Safety

Backed enums can be converted to their scalar values when writing to a database. When reading a record, OrderStatus::from() reconstructs the enum and throws ValueError if the stored value is invalid.

$storedStatus = 'paid';

$status = OrderStatus::from($storedStatus);

echo $status->name, PHP_EOL;
// Paid

$unknown = OrderStatus::tryFrom('archived');

var_dump($unknown);
// NULL

The distinction between from() and tryFrom() is useful. An unexpected value in a database record may indicate data corruption or an incomplete migration, while an unknown value received from an external integration may be something the application expects to handle gracefully.

Database constraints still matter. An enum in PHP does not prevent another application, SQL script, or administrator from writing an invalid status directly into the database.

The Concurrency Problem Remains

Type safety does not automatically provide transactional safety. Imagine two workers loading the same pending order. One marks it paid while another attempts to cancel it. Each may evaluate a valid transition against stale information.

A production implementation should enforce the expected current state during persistence, for example through an UPDATE statement that includes the previous status in its WHERE clause, or through an appropriate transactional locking strategy.

Domain validation and database concurrency control solve different problems. Both are required when several requests or workers can modify the same business entity.

When an Enum Is Not Enough

An enum works well when the set of states is relatively stable and the transition rules are straightforward. It becomes less suitable when workflows are dynamically configured by customers, stored as data, or governed by many independent conditions.

In those situations, a dedicated workflow service or state machine may be more appropriate. Permissions, inventory availability, payment-provider results, and other external conditions should not necessarily be embedded inside an enum.

The useful principle is to make illegal transitions difficult, keep the business vocabulary consistent, and choose an abstraction proportional to the complexity of the workflow.

PHP enums provide a strong foundation for that approach. Their real value is not eliminating strings; it is making business states and the rules surrounding them visible in the code.

LEAVE A REPLY

Please enter your comment!
Please enter your name here