Why typed collections
A PHP array says nothing about what is in it. array $users may hold users, ids, null, or a user and an order, and every function that receives it either trusts the caller or checks again. PHPDoc (list<User>) helps static analysis, but nothing stops a wrong value at runtime, and nothing carries the rules of the domain: that an order has at least one line, that a cart has one line per product, that a transaction balances.
A collection class fixes both:
php
/** @extends ImmutableList<User> */
final readonly class Users extends ImmutableList
{
protected const TYPE = User::class;
}
function notify(Users $users): void { /* every element is a User, guaranteed */ }- The type is checked when data enters.
Users::of($order)throwsInvalidElementType: Users[0] expects User, got Order.The rest of the code never checks again. - PHPStan knows it too.
Users::of($order)is an error before you run anything;$users->first()is aUser;$users->filter(...)is stillUsers. - The domain rules live with the data. An invariant in
assertInvariants()runs for every new instance, including the results offilter(),remove()andslice(), so no operation can produce a broken collection. - Nothing changes behind your back. A collection passed to another function or stored in an object stays as it was. Every operation returns a new one.
When not to use them
- Hot loops over millions of scalars. A collection is an object around an array; for raw number crunching, an array is faster. For building collections in a loop, use a builder, which is close to array speed.
- Data you only pass through. A decoded JSON payload that goes straight into a template does not need a type.
- You need mutation. These collections are immutable by design; there is no mutable variant.
Compared with other libraries
| Element type checked at runtime | Immutable | Domain subclasses with invariants | |
|---|---|---|---|
| PHP arrays + PHPDoc | no | no | no |
| ramsey/collection | yes | no | subclasses, no invariant hook |
| loophp/collection, noctud/collection | no | yes | no |
| eugeneerg/collections | yes | yes | yes |
The niche is the combination: immutable collections whose element type is enforced at runtime and checked statically, declared as small domain classes.