PHP Generics That Work Today: A Practical Guide
Native generics in the PHP engine remain a future dream, but static analysis with PHPStan and Psalm lets us write 100% type-safe generic code today. Here is how to master @template in practice.
Engineering context & problem
The PHP Zend Engine lacks native runtime support for generic types. This pushes developers toward untyped arrays (mixed[]), repetitive boilerplate instanceof checks, and broken IDE autocomplete across custom collections and repositories.
Architectural approach & solution
We leverage @template, @param class-string<T>, and @return T annotations. The PHP runtime ignores them as plain comments (zero runtime performance penalty), while PHPStan and modern IDEs enforce them as a first-class generic type system.
Core code snippet & configuration
<?php
declare(strict_types=1);
namespace App\Infrastructure\Repository;
use Doctrine\ORM\EntityManagerInterface;
/**
* @template T of object
*/
final class GenericRepository
{
/**
* @param class-string<T> $entityClass
*/
public function __construct(
private readonly EntityManagerInterface $em,
private readonly string $entityClass
) {}
/**
* @return T|null
*/
public function findById(int|string $id): ?object
{
return $this->em->find($this->entityClass, $id);
}
/**
* @return list<T>
*/
public function findAll(): array
{
return $this->em->getRepository($this->entityClass)->findAll();
}
}Key takeaways & engineering rules
PHP generics operate on an informal contract between PHPDoc annotations (@template) and static analysis tools (PHPStan, Psalm).
Generic Repository<T> and Collection<T> patterns eliminate brittle type-casting and dozens of boilerplate wrapper classes.
Strict static analysis (PHPStan Level 8+) in CI catches type mismatches before production, delivering type guarantees on par with compiled languages.
Trade-offs & when NOT to use
Because verification happens exclusively at static analysis time, skipping CI checks or bypassing types via reflection will not trigger a runtime error from the PHP engine. Rigid CI pipeline enforcement is non-negotiable.
Summary
A comprehensive deep dive into practical PHP generics: from core @template syntax and type variance to PHPStan CI integration and what the future holds for native PHP typing.
Full article with source code
Want to read the full article with deep implementation details?
Click below to access the complete story on Medium with zero paywalls (free access enabled via author friend link).
Looking for backend architecture guidance?
I help teams modernize legacy monoliths, containerize workloads, and build pragmatic AI tooling.