PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
155: Attributes (Annotations) in PHP 8
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
SecretVaultclass with two methods:openSafe()(which requires the 'admin' role) andviewLogs()(which requires the 'manager' role). - Create a
Guardclass with a methodcanAccess(object $object, string $method, string $userRole). This method should:- Use Reflection to check if the specified method on the object has the
RequiredRoleattribute. - If the attribute exists, compare the required role with the
$userRoleprovided. - Return
trueif the roles match or if no attribute is present; returnfalseif the roles do not match.
- Use Reflection to check if the specified method on the object has the
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).
There are no comments for now.