Skip to content

Domain collections ​

A collection class is a value object of your domain. It has a name from the domain, methods that speak its language, and rules that always hold.

Methods ​

php
/** @extends ImmutableList<OrderLine> */
final readonly class OrderLines extends ImmutableList
{
    protected const TYPE = OrderLine::class;

    public function total(): Money
    {
        return $this->reduce(fn(Money $sum, OrderLine $line) => $sum->add($line->total()), Money::zero());
    }

    public function forProduct(Sku $sku): self
    {
        return $this->filter(fn(OrderLine $line) => $line->sku->value === $sku->value);
    }
}

Operations like filter(), sort() and append() return static, so forProduct() returns OrderLines, with its total().

Invariants ​

assertInvariants() runs for every new instance: when it is created, and after every operation.

php
protected function assertInvariants(): void
{
    if ($this->isEmpty()) {
        throw new EmptyOrder();
    }
}

Now no code path can produce an empty OrderLines: not the constructor, not filter(), not remove(), not unserialize() from a cache.

Invariants may use the collection's own operations. $this->unique() or $this->filter(...) inside assertInvariants() create temporaries that skip their own check (otherwise the check would recurse forever). A temporary must not outlive the check: keeping one, for example in a property, throws UncheckedInstanceEscaped.

php
protected function assertInvariants(): void
{
    if ($this->count() !== $this->uniqueBy(fn(CartLine $l) => $l->product->sku)->count()) {
        throw new DomainException('A product appears in two cart lines.');
    }
}

Throw your own exceptions here: they are domain errors, and the library does not wrap them.

Union and scalar types ​

php
protected const TYPE = [Cat::class, Dog::class];   // @extends ImmutableList<Cat|Dog>
protected const TYPE = [User::class, 'null'];      // @extends ImmutableList<User|null>
protected const TYPE = ['int', 'string'];          // @extends ImmutableList<int|string>

Ready-made scalar lists: IntList and FloatList with sum(), average(), min(), max(); StringList with join().

Types a constant cannot express ​

Override elementType() with a CallbackType:

php
/** @extends ImmutableList<positive-int> */
final readonly class Quantities extends ImmutableList
{
    protected static function elementType(): Type
    {
        return new CallbackType(static fn(mixed $v): bool => is_int($v) && $v > 0, 'positive-int');
    }
}

The second argument is the name used in error messages.

Maps and sets ​

The same pattern, with KEY_TYPE and VALUE_TYPE for maps:

php
/** @extends ImmutableMap<UserId, User> */
final readonly class UsersById extends ImmutableMap
{
    protected const KEY_TYPE = UserId::class;
    protected const VALUE_TYPE = User::class;
}

/** @extends ImmutableSet<Tag> */
final readonly class Tags extends ImmutableSet
{
    protected const TYPE = Tag::class;
}

Identity ​

Objects are compared by instance. A value object that should be equal to another instance with the same value implements Hashable:

php
final readonly class Sku implements Hashable
{
    public function __construct(public string $value) {}

    public function identity(): string
    {
        return $this->value;
    }
}

The rule is the same everywhere: map keys, sets, contains(), indexOf(), unique(), uniqueBy() and equals().