Skip to Content
Course content

155: Attributes (Annotations) in PHP 8

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was maintaining a legacy API that relied heavily on DocBlocks for everything—routing, validation, and caching. I remember spending an entire afternoon hunting down a bug where a route wasn't working, only to find that someone had accidentally put a space in the middle of a @Route annotation. Because DocBlocks are just comments, the PHP engine ignored the typo completely. The code was syntactically correct, but the application logic was broken. It felt like I was debugging a string inside a comment, which is a special kind of hell for any developer.

PHP 8 finally fixed this by introducing Attributes. Instead of hacking comments to store metadata, we now have a native way to attach structured data directly to classes, methods, and properties. These aren't "annotations" in the Java sense—which are often processed at compile time—but rather metadata that lives in the PHP AST and can be queried at runtime via the Reflection API. If you mistype an attribute name now, you'll actually get a warning or an error, which is exactly what we want.

The Shift from Comments to Native Metadata

The syntax is immediately recognizable: it's the #[Attribute] notation. While it looks like a comment, it's actually a first-class citizen of the language. When you define an attribute, you're essentially creating a class that acts as a container for that metadata.

#[Attribute]
class Required {
    public string $message = "This field is mandatory";
}

class UserRegistration {
    #[Required(message: "You must provide an email address")]
    public string $email;
}

In the example above, #[Required] isn't executing any code when the UserRegistration class is instantiated. It's just sitting there, tagged onto the $email property. I like to think of attributes as "sticky notes" for the compiler and other parts of your code to find later. They don't change how the property behaves by themselves; they just describe it.

Extracting Metadata with the Reflection API

Since attributes don't "do" anything on their own, you need a way to read them. This is where the Reflection API comes into play. You use Reflection to inspect a class or property and ask, "Hey, do you have any attributes of this specific type attached to you?"

Here is how I typically handle this when building a custom validator:

$reflection = new ReflectionProperty(UserRegistration::class, 'email');
$attributes = $reflection->getAttributes(Required::class);

foreach ($attributes as $attribute) {
    // The 'newInstance()' method actually creates the instance of the attribute class
    $required = $attribute->newInstance();
    echo "Validation error: " . $required->message;
}

One detail that often trips people up is the difference between the ReflectionAttribute object and the actual attribute class instance. getAttributes() returns an array of ReflectionAttribute objects. To get the actual data (like the $message property), you have to call newInstance(). It's a small extra step, but it keeps the reflection process efficient by not instantiating every attribute unless you actually need to use it.

Structuring Attributes for Flexibility

You can make your attributes more flexible by using the Attribute target flag. By default, an attribute can be put anywhere, but in a professional codebase, you want to restrict where your metadata can live. There's no reason a #[Route] attribute should be allowed on a class property, right?

You can constrain this using Attribute::TARGET_METHOD, Attribute::TARGET_CLASS, or a combination of them using the bitwise OR operator (|). I always recommend doing this; it prevents other developers on your team from putting your custom tags in places that make no sense, saving you from writing a bunch of "if this is a property, ignore it" logic in your reflection code.

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class CacheResult {
    public function __construct(public int $ttl = 3600) {}
}

Now, if someone tries to put #[CacheResult] on a class property, PHP will throw an Error. It's a great way to enforce a "contract" for how your metadata is used throughout the project.




📋 Practical Task

Building a Role-Based Method Guard

Your task is to create a simple system that restricts access to certain methods based on a user's role. You will need to implement the attribute and a "Guard" class that checks if the current user has the required permission.

Requirements:

  • Create an attribute class called RequiredRole. It should only be allowed on methods and should accept a string (the role name) in its constructor.
  • Create a SecretVault class with two methods: openSafe() (which requires the 'admin' role) and viewLogs() (which requires the 'manager' role).
  • Create a Guard class with a method canAccess(object $object, string $method, string $userRole). This method should:
    • Use Reflection to check if the specified method on the object has the RequiredRole attribute.
    • If the attribute exists, compare the required role with the $userRole provided.
    • Return true if the roles match or if no attribute is present; return false if the roles do not match.

Testing your code:
Instantiate the Guard and the SecretVault. Test it by trying to access openSafe() as a 'manager' (should fail) and as an 'admin' (should succeed).

Rating
0 0

There are no comments for now.

to be the first to leave a comment.