Make PHP Domain Data Safer with Readonly Value Objects and Enums

Tim Rabbetts | November 22, 2026

Many PHP applications begin with arrays. An HTTP request becomes an array, a database row becomes an array, and an array is passed through controllers, services, jobs and templates. This is convenient, but it also makes invalid states easy to create. A misspelled status, an empty currency code or a negative price can travel a long way before anything fails.

PHP gives you language features that can move those failures closer to the boundary where bad data enters the system. Enums model a finite set of legal choices, while readonly classes and readonly properties help represent data that should not change after construction. Used together, they provide a lightweight way to build value objects: small objects defined by their values rather than by an identity or database record.

This is not an argument for wrapping every scalar in a class. It is a practical approach for data with rules that matter: money, email addresses, order states, country codes, identifiers and other concepts that are more precise than their underlying PHP type.

Why arrays and strings become expensive

Consider an order assembled from loosely typed input:

$order = [
    'status' => 'paid',
    'currency' => 'GBP',
    'total' => 1499,
];

Nothing in this structure tells another developer whether total means pennies or pounds. The application might use GBP in one place and gbp in another. A future refactor could change paid to complete without finding every consumer.

PHPDoc annotations can document these conventions, but documentation does not enforce them at runtime. An enum can restrict a value to a known set of cases, and a value object can reject invalid input before it enters the rest of the application. PHP's documentation describes enums as custom types limited to a discrete set of possible values, which is precisely the problem they solve here. See the PHP enum overview. ([php.net](https://www.php.net/manual/en/language.enumerations.overview.php?utm_source=openai))

Prerequisites and design rules

The examples use PHP 8.2 or later because readonly classes were introduced in PHP 8.2. Enums require PHP 8.1 or later. If your application still supports PHP 8.1, the same design works with individual readonly properties instead of a readonly class. The PHP manual documents that a readonly class applies readonly behaviour to its declared properties and prevents dynamic properties. Read the readonly class reference. ([php.net](https://www.php.net/oop5.basic?utm_source=openai))

Before writing a class, establish four rules:

  • Validate external input at a boundary such as a request handler, message consumer or repository.
  • Store values in a canonical form, such as uppercase currency codes or lowercase email addresses.
  • Do not expose setters for data that should be stable after construction.
  • Keep domain behaviour with the data it needs, but keep infrastructure concerns such as database queries outside the value object.

A value object should be small and predictable. It should not call an API, read from a global variable or query the database in its constructor. Construction should be cheap, deterministic and safe to repeat.

Start with a backed enum for order status

An order status is a good enum candidate because the valid values are known by the application. A backed enum gives each case a scalar representation, which is useful when writing to a database or sending JSON.

<?php

declare(strict_types=1);

namespace App\Domain\Order;

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Cancelled = 'cancelled';
    case Fulfilled = 'fulfilled';

    public function canBeCancelled(): bool
    {
        return match ($this) {
            self::Pending, self::Paid => true,
            self::Cancelled, self::Fulfilled => false,
        };
    }

    public function isFinal(): bool
    {
        return match ($this) {
            self::Cancelled, self::Fulfilled => true,
            self::Pending, self::Paid => false,
        };
    }
}

The enum is now both a type and a home for status-related rules. A service can accept OrderStatus rather than an arbitrary string:

function cancelOrder(OrderStatus $status): OrderStatus
{
    if (!$status->canBeCancelled()) {
        throw new \DomainException('This order cannot be cancelled.');
    }

    return OrderStatus::Cancelled;
}

When reading a stored value, use OrderStatus::tryFrom() if invalid data should be handled as a normal application error, or OrderStatus::from() if invalid data indicates a programming or data-integrity failure.

$storedStatus = 'paid';

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

if ($status === null) {
    throw new \UnexpectedValueException('Unknown order status.');
}

Do not blindly pass user-controlled strings to from() without deciding how the resulting ValueError should be handled. At an HTTP boundary, a controlled validation response is usually better than an uncaught exception.

Build a money value object

Money is a classic example of data that should not be represented by a floating-point number. Store the minor unit as an integer: pence for GBP, cents for USD or another smallest practical unit for the currency. This avoids representing a price such as 10.10 as a binary floating-point value and makes arithmetic easier to reason about.

The example below validates the amount and currency code, then exposes operations that return new objects. The original object remains unchanged.

<?php

declare(strict_types=1);

namespace App\Domain\Money;

use InvalidArgumentException;

readonly class Money
{
    public function __construct(
        public int $minorAmount,
        public string $currency,
    ) {
        $currency = strtoupper($currency);

        if (!preg_match('/^[A-Z]{3}$/', $currency)) {
            throw new InvalidArgumentException(
                'Currency must be a three-letter ISO-style code.'
            );
        }

        if ($minorAmount < 0) {
            throw new InvalidArgumentException(
                'Money cannot have a negative amount.'
            );
        }

        // A promoted readonly property has already been assigned here.
        // Canonicalisation is therefore handled by the named constructor.
    }

    public static function fromMinor(int $minorAmount, string $currency): self
    {
        $currency = strtoupper(trim($currency));

        if (!preg_match('/^[A-Z]{3}$/', $currency)) {
            throw new InvalidArgumentException(
                'Currency must be a three-letter ISO-style code.'
            );
        }

        if ($minorAmount < 0) {
            throw new InvalidArgumentException(
                'Money cannot have a negative amount.'
            );
        }

        return new self($minorAmount, $currency);
    }

    public function add(self $other): self
    {
        $this->assertSameCurrency($other);

        return self::fromMinor(
            $this->minorAmount + $other->minorAmount,
            $this->currency,
        );
    }

    public function subtract(self $other): self
    {
        $this->assertSameCurrency($other);

        if ($other->minorAmount > $this->minorAmount) {
            throw new InvalidArgumentException(
                'The result cannot be negative.'
            );
        }

        return self::fromMinor(
            $this->minorAmount - $other->minorAmount,
            $this->currency,
        );
    }

    private function assertSameCurrency(self $other): void
    {
        if ($this->currency !== $other->currency) {
            throw new InvalidArgumentException(
                'Money values must use the same currency.'
            );
        }
    }
}

There is an important detail in this example: promoted properties are assigned before the constructor body runs. That means a constructor cannot simply modify a promoted readonly property after promotion. The named constructor normalises input before calling the real constructor, but the public constructor still needs a clear contract.

A cleaner production design is to make the main constructor private and require callers to use the named constructor:

readonly class Money
{
    private function __construct(
        public int $minorAmount,
        public string $currency,
    ) {
    }

    public static function fromMinor(int $minorAmount, string $currency): self
    {
        $currency = strtoupper(trim($currency));

        if ($minorAmount < 0) {
            throw new \InvalidArgumentException(
                'Amount cannot be negative.'
            );
        }

        if (!preg_match('/^[A-Z]{3}$/', $currency)) {
            throw new \InvalidArgumentException(
                'Currency must be a three-letter code.'
            );
        }

        return new self($minorAmount, $currency);
    }
}

This prevents callers from bypassing normalisation. If you need to accept decimal input such as 14.99, parse it explicitly at the input boundary and convert it to minor units using a well-defined rounding policy. Do not rely on an implicit cast from a floating-point value. For high-precision financial calculations, involve a suitable decimal or money library rather than attempting to build a complete monetary system around integers alone.

Use value objects at application boundaries

Suppose a controller receives JSON for an order. The controller should translate transport data into domain types. The rest of the application should not need to know whether the request used a string, integer or JSON field.

$payload = json_decode(
    $requestBody,
    true,
    512,
    JSON_THROW_ON_ERROR,
);

$status = OrderStatus::tryFrom($payload['status'] ?? '');

if ($status === null) {
    throw new \InvalidArgumentException('Invalid order status.');
}

$total = Money::fromMinor(
    (int) ($payload['total_minor'] ?? -1),
    (string) ($payload['currency'] ?? ''),
);

$service->placeOrder($status, $total);

Type declarations do not replace validation. The cast to int above is only appropriate if the API contract has already established that the field is an integer-like value. For untrusted input, check the shape and type before converting. Otherwise, values such as malformed strings may be silently coerced into data that appears valid.

For JSON APIs, create an explicit serialisation format rather than exposing an object's internal structure by accident:

final class OrderResponse
{
    public static function from(OrderStatus $status, Money $total): array
    {
        return [
            'status' => $status->value,
            'total_minor' => $total->minorAmount,
            'currency' => $total->currency,
        ];
    }
}

This gives the API a stable contract even if the internal classes later gain methods or private implementation details. It also makes it obvious which values are safe to expose.

Readonly does not mean deeply immutable

A readonly property cannot be reassigned after initialisation, but readonly does not automatically freeze an object stored inside that property. The PHP manual calls this interior mutability: the reference cannot be replaced, but the referenced object may still change internally. See the PHP properties reference. ([php.net](https://www.php.net/manual/en/language.oop5.properties.php?utm_source=openai))

readonly class Basket
{
    public function __construct(
        public \ArrayObject $items,
    ) {
    }
}

$basket = new Basket(new \ArrayObject());
$basket->items->append('item'); // The object inside is still mutable.

For value objects, prefer scalar properties, enums and other immutable value objects. If a readonly class contains a mutable collection, do not assume callers see a frozen snapshot. Return copies or immutable collection types where the application requires stronger guarantees.

Testing the invariants, not the implementation

The most valuable tests for a value object describe what must always be true. You do not need a large test suite to get useful protection.

  1. Valid input creates the expected value.
  2. Invalid input throws the expected exception.
  3. Operations preserve important invariants such as currency compatibility.
  4. Operations return a new value without changing the original.
  5. Enum cases cover every permitted state and every transition rule.
public function testAddingMoneyDoesNotMutateEitherOperand(): void
{
    $first = Money::fromMinor(1000, 'gbp');
    $second = Money::fromMinor(250, 'GBP');

    $result = $first->add($second);

    self::assertSame(1000, $first->minorAmount);
    self::assertSame(250, $second->minorAmount);
    self::assertSame(1250, $result->minorAmount);
    self::assertSame('GBP', $result->currency);
}

Also test the boundaries that tend to cause production defects: zero, very large integers, whitespace, lowercase codes, mismatched currencies and malformed external values. If the application accepts decimal money, test rounding decisions explicitly rather than relying on examples that happen to divide cleanly.

Security and persistence considerations

Value objects improve security by reducing ambiguity, but they do not make input trusted. Continue to apply authentication, authorisation, output escaping, CSRF protection and database parameterisation where appropriate. A valid Money object only proves that an amount has the expected shape; it does not prove that the current user is allowed to charge it.

Be cautious when serialising objects. PHP serialisation can recreate objects and depends on the class definition being available. The PHP manual documents serialize() and unserialize(), while also describing the dedicated __serialize() and __unserialize() hooks. Read the object serialisation guidance. ([php.net](https://www.php.net/manual/en/language.oop5.serialization.php?utm_source=openai))

Do not unserialise untrusted data. For queues, caches and APIs, prefer an explicit array or JSON representation with a versioned schema. Reconstruct the value object through its validating factory when data comes back out of storage. This prevents a cache or message payload from bypassing the normal construction rules.

Performance and when not to use this approach

A small value object has a cost: it allocates an object and may perform validation. In most web applications, that cost is modest compared with database queries, network calls and template rendering. Nevertheless, avoid wrapping millions of rows in multiple objects inside a memory-sensitive batch process without measuring.

Use value objects where they remove meaningful ambiguity or centralise important rules. Do not create classes merely to rename a scalar. A local integer used only inside a short calculation probably does not need a MinorAmount class. A price crossing payment, invoicing and reporting boundaries probably does.

For large imports, validate and normalise in batches, stream records instead of loading the entire dataset, and measure memory usage with realistic data. The design goal is not “maximum object orientation”; it is making invalid data difficult to represent while keeping hot paths understandable.

A practical adoption plan

  1. Choose one concept with recurring validation bugs, such as an order status or currency code.
  2. Write down its legal states and canonical representation.
  3. Create an enum or readonly value object with a small public API.
  4. Convert external input at one boundary rather than throughout the codebase.
  5. Replace the most important string or array parameters with the new type.
  6. Add tests for invalid input, boundary values and business rules.
  7. Define explicit database and JSON conversion methods.
  8. Measure memory and execution time if applying the change to a high-volume batch path.

PHP does not require a framework to benefit from this style. Enums express finite choices, readonly classes protect stable data, and named constructors make validation visible. Together they turn vague conventions into executable rules. The result is code that documents itself through its types and fails earlier, closer to the source of bad data.