Getting started
Install
bash
composer require eugeneerg/collectionsPHP 8.2 or newer, no runtime dependencies. If your project uses PHPStan, it needs version 2.3.7 or newer; Composer refuses older ones, which report false errors for the type check.
Your first collection
php
use EugeneErg\Collections\ImmutableList;
/** @extends ImmutableList<User> */
final readonly class Users extends ImmutableList
{
protected const TYPE = User::class;
}Three things make a collection class:
extends ImmutableList(orImmutableMap,ImmutableSet). The class must bereadonly; PHP requires it of subclasses of readonly classes.TYPE: what the elements are. A class, interface or enum, one of'int','float','string','bool','null', or a list of them for a union.@extends ImmutableList<User>: the same type for static analysis. The PHPStan extension checks that it matchesTYPE.
Use it
php
$users = Users::of($alice, $bob);
$users = Users::fromIterable($repository->findAll());
$admins = $users->filter(fn(User $u) => $u->isAdmin()); // Users
$names = $users->map(fn(User $u) => $u->name); // ImmutableList<string>
$first = $users->first(); // User, or ElementNotFound
$maybe = $users->firstOrNull(); // User|null
$users->append($carol); // a new Users; $users is unchanged
Users::of($order); // InvalidElementType: Users[0] expects User, got Order.Turn on the PHPStan extension
neon
# phpstan.neon
includes:
- vendor/eugeneerg/collections/extension.neonGenerics work without it; the extension adds the check that TYPE matches @extends. See Static analysis.
Next
- Give the collection its own methods and rules: Domain collections.
- Lists, sets, maps and builders: Lists, sets and maps.
- Every method: the reference.