Attributes via reflection

An attribute in PHP is a note written in the code, and reflection is the reader that turns the note into an object. The four blocks go from finding the note to caching what the reader learned.

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.

<?php #[Attribute] class Route { public function __construct(public string $path = "") { } } #[Route(path: "/users")] class UserController { } $ref = new ReflectionClass(UserController::class); echo count($ref->getAttributes(Route::class)), PHP_EOL; echo $ref->getAttributes(Route::class)[0]->getName(), PHP_EOL;

php read.php

1
Route

The class carried one attribute of that type, and the entry names the attribute class without building an object yet.

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.

<?php #[Attribute] class Route { public function __construct(public string $path = "") { } } #[Route(path: "/users")] class UserController { } $ref = new ReflectionClass(UserController::class); $list = $ref->getAttributes(Route::class); $route = $list[0]->newInstance(); echo $route->path, PHP_EOL; echo get_class($route), PHP_EOL;

php args.php

/users
Route

The bracket value landed in the promoted property, and the object is an ordinary instance of the attribute class.

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.

<?php #[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 $prop->getName(), " needs ", $rule->min, PHP_EOL; $value = $prop->getValue($user); echo strlen($value) < $rule->min ? "too short" : "ok", PHP_EOL; } }

php validate.php

name needs 3
too short

The loop found the rule on the property, read the minimum from the attribute object and compared it with the current value.

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.

<?php #[Attribute] class Route { public static int $made = 0; public function __construct(public string $path = "") { self::$made++; } } #[Route(path: "/users")] class UserController { } $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), PHP_EOL; echo routeOf(UserController::class), PHP_EOL; echo Route::$made, PHP_EOL;

php cache.php

/users
/users
1

The second call answered from the array, and the counter in the attribute constructor proves that only one object was built.

Exercises

  1. Add a second attribute to the controller and list both names with reflection.
  2. Give Route a second argument with a default and read it from newInstance().
  3. Add a MaxLength rule and check both rules in one loop.
  4. Cache the route of two classes and print how many attribute objects were created.
  5. Explain why reflection is slow enough to deserve a cache in a router.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which class reads attributes at run time?

    Answer

    ReflectionClass

    ReflectionClass and its method getAttributes() return the attribute entries of a class.

  2. What does newInstance() on an attribute entry do?

    Answer

    It builds an object of the attribute class with the given arguments

    The entry knows the class and the arguments, so newInstance() hands back a real attribute object.

  3. Which target does Attribute::TARGET_PROPERTY allow?

    Answer

    Properties

    The constant limits where PHP accepts the attribute, and a property rule belongs on a property.

  4. Why cache the result of a reflection lookup?

    Answer

    Because parsing the metadata costs more than an array lookup

    A lookup walks the class metadata, so a keyed array saves that work on every later call.

  5. What does this program print? <?php #[Attribute] class Route { public function __construct(public string $path = "") { } } #[Route(path: "/users")] class UserController { } $ref = new ReflectionClass(UserController::class); echo count($ref->getAttributes(Route::class));

    Answer

    1

    One Route attribute sits on the class, so the list has one entry.

  6. What does this program print? <?php #[Attribute] class Route { public function __construct(public string $path = "") { } } #[Route(path: "/users")] class UserController { } $ref = new ReflectionClass(UserController::class); $list = $ref->getAttributes(Route::class); echo $list[0]->newInstance()->path;

    Answer

    /users

    newInstance() passes the bracket value to the constructor, and the promoted property prints it.

  7. What does this program print? <?php #[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) { echo $attr->newInstance()->min; } }

    Answer

    3

    The property carries the rule, and the attribute object reports the minimum it was given.

  8. What does $prop->getValue($user) return in a validation loop?

    Answer

    The current value of that property on the object

    The reflection property reads the live value from the instance that was passed in.

  9. What does this program print? <?php #[Attribute] class Route { public static int $made = 0; public function __construct(public string $path = "") { self::$made++; } } #[Route(path: "/users")] class UserController { } $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]; } routeOf(UserController::class); routeOf(UserController::class); echo Route::$made;

    Answer

    1

    The second call hits the cache, so the attribute constructor ran only once.

  10. What does the #[Attribute] marker on a class do?

    Answer

    It allows the class to be used as an attribute

    Without the marker PHP refuses to use the class in the attribute position.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev