PHP code example of tcds-io / php-better-generics

1. Go to this page and download the library: Download tcds-io/php-better-generics library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tcds-io / php-better-generics example snippets


use function Tcds\Io\Generic\listOf;
use function Tcds\Io\Generic\mapOf;

$users = listOf($alice, $bob, $carol);

$names = $users
    ->filter(fn (User $u) => $u->isActive())
    ->map(fn (User $u) => $u->name);

$byEmail = $users->indexedBy(fn (User $u) => $u->email);
// Map<string, User>

$first = $users->first(fn (User $u) => $u->isAdmin());
$count = $users->count(fn (User $u) => $u->isActive());

use function lazyOf;
use function lazyBufferOf;

// Single proxy: $user is fully typed as User; constructor only runs on first access.
$user = lazyOf(User::class, fn () => $userRepository->find($id));

// Buffered loader: collects keys, then loads in one batch when the buffer fills.
$loader = lazyBufferOf(
    User::class,
    fn (array $ids) => $userRepository->findMany($ids),
    maxBufferSize: 50,
);

$users = $orderIds->map(fn (string $orderId) => $loader->lazyOf($orderId));
// Each access fetches up to 50 users at once instead of N+1.

use Tcds\Io\Generic\Reflection\ReflectionClass;

/** @template T */
class Collection {
    /** @return list<T> */
    public function items(): array { /* ... */ }
}

/** @extends Collection<User> */
class UserCollection extends Collection {}

$reflection = new ReflectionClass(UserCollection::class);

$type = $reflection->getMethod('items')->getReturnType();
// GenericReflectionType('list', [User::class])
// — `T` resolved through `@extends Collection<User>`.