Attributes via reflection

Read with reflection

Attributes add metadata to classes, methods, and properties. Reflection lists them at runtime without running the marked code first.

Get a ReflectionClass for the target, ask for attributes of one type, and inspect what was found.

#[Attribute] class Route { public function __construct(public string $path = "") {} } #[Route(path: "/users")] class UserController { } $ref = new ReflectionClass(UserController::class); var_dump($ref->getAttributes(Route::class));

Attribute arguments

Each attribute entry can create a real object with newInstance. Constructor values passed in brackets become object state.

After that step the metadata behaves like any plain object with public fields and methods.

$ref = new ReflectionClass(UserController::class); $list = $ref->getAttributes(Route::class); $route = $list[0]->newInstance(); echo $route->path;

Build a validator

Attributes shine for validation rules placed next to properties. A short loop reads the rules and checks each value in turn.

Adding a new rule means adding a new attribute, while the checking loop stays the same.

#[Attribute(Attribute::TARGET_PROPERTY)] class MinLength { public function __construct(public int $min = 0) {} } class User { #[MinLength(min: 3)] public string $name = "Al"; } $user = new User(); $pref = new ReflectionClass($user); foreach ($pref->getProperties() as $prop) { foreach ($prop->getAttributes(MinLength::class) as $attr) { $rule = $attr->newInstance(); echo $rule->min; } }

Cache reflection

Reflection parses a lot of detail, so repeated lookups deserve a cache. Parse once per class name and reuse the result on later calls.

A simple array keyed by class name removes most of the cost in routers and validators.

$cache = []; function routeOf(string $class): string { global $cache; if (!isset($cache[$class])) { $ref = new ReflectionClass($class); $found = $ref->getAttributes(Route::class); $cache[$class] = $found[0]->newInstance()->path; } return $cache[$class]; } echo routeOf(UserController::class);

Next: Closure binding

Article author: Arthur Isaev