Table of Contents

4. Attributes — Adding Meaning Without Adding Weight

Modern PHP gives us a quiet, declarative way to attach structure and intent to our code.
Attributes don’t change behavior by themselves.
They describe behavior
— and let tools, frameworks, and libraries respond to it.

They’re one of the clearest examples of how PHP 8+ thinks:
metadata belongs next to the code it describes.


1. What Attributes Are

Attributes are structured metadata.
They annotate classes, methods, properties, or parameters with information that other systems can read.

They replace:

Attributes make intent explicit and machine‑readable.


2. Why Modern PHP Uses Them

Attributes reduce friction:

Frameworks like Symfony, Laravel, Doctrine, and PHPUnit rely on attributes because they keep configuration close to the code and in sync with the code.


3. The Mental Model

Attributes are declarative signals.

They don’t do anything on their own.
They simply describe how something should be interpreted.

A framework, library, or tool reads the attribute and decides what to do.

This is the key mental model:

Attributes describe structure and intent.
Behavior lives elsewhere.


4. A Simple Example

#[Route('/profile')]
class ProfileController
{
    #[Get]
    public function show(): Response
    {
        // ...
    }
}

The attributes don’t execute logic.
They tell the router how to treat this class and method.


5. When to Use Attributes

Use attributes when:

Attributes shine when they replace scattered configuration
with a single, readable declaration.


6. When Not to Use Attributes

Avoid attributes when:

Attributes are for description,
not decision‑making.

When AI Gets This Wrong

AI often invents attributes, misplaces them, or uses them where configuration or code would be clearer. Sometimes it adds attributes that don’t exist, or mixes frameworks, or treats attributes as if they execute logic. Our mental model helps us see when an attribute is appropriate — and when AI is using one simply because it “looks modern”.


Summary

Attributes let us express intent without adding weight.
They keep metadata close to the code, reduce configuration, and make structure explicit.

Once we internalize this, we can immediately see when AI‑generated code:

Attributes are a quiet part of modern PHP
— but they shape how the language wants to be read.