Skip to content

Getting started ​

Install ​

bash
composer require eugeneerg/collections

PHP 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:

  1. extends ImmutableList (or ImmutableMap, ImmutableSet). The class must be readonly; PHP requires it of subclasses of readonly classes.
  2. 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.
  3. @extends ImmutableList<User>: the same type for static analysis. The PHPStan extension checks that it matches TYPE.

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.neon

Generics work without it; the extension adds the check that TYPE matches @extends. See Static analysis.

Next ​