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
32: Attributes
When you first encounter Attributes in PHP 8, it's incredibly easy to fall into a trap. Because they look exactly like annotations in Java or decorators in Python, most developers assume that adding #[SomeAttribute] above a method automatically "triggers" some behavior in the background. They think the PHP engine sees that tag and says, "Oh, I should run the logic inside SomeAttribute now."
Attributes aren't magic function calls
Let's prove that. Imagine you're building a simple API and you want to mark certain methods as "Admin Only." You might write something like this:
#[Attribute]
class AdminOnly {}
class UserController {
#[AdminOnly]
public function deleteUser(int $id) {
echo "User deleted!";
}
}
$controller = new UserController();
$controller->deleteUser(123);
If you run this, the output is simply "User deleted!". The #[AdminOnly] attribute didn't stop the execution, it didn't check a session, and it didn't throw an exception. It did absolutely nothing. I've seen junior devs spend hours wondering why their "security attribute" wasn't working, only to realize they were expecting the language to provide the execution logic for them.
Reflection is the engine that makes them useful
Here is the reality: Attributes are just structured metadata. They are like sticky notes attached to your code. A sticky note that says "Fragile" doesn't actually make a box fragile; it just tells whoever is handling the box that they should be careful. To make an Attribute "do" something, you have to write the code that reads the note.
In PHP, we do this using the Reflection API. You ask PHP to look at a class or method, check if a specific attribute is present, and then execute your own logic based on that finding. Here is how we actually make that AdminOnly example work:
#[Attribute]
class AdminOnly {}
class UserController {
#[AdminOnly]
public function deleteUser(int $id) {
echo "User deleted!";
}
}
$controller = new UserController();
$reflection = new ReflectionMethod($controller, 'deleteUser');
$attributes = $reflection->getAttributes(AdminOnly::class);
if (!empty($attributes)) {
echo "Wait! This method requires admin privileges. Checking permissions... \n";
// In a real app, you'd check your Auth service here.
}
$controller->deleteUser(123);
Now the logic is decoupled. The UserController doesn't need to know how permission checking works; it just declares that it needs it. The "Dispatcher" or "Router" handles the actual enforcement.
Creating dynamic attributes with arguments
Attributes become truly powerful when you pass data into them. You aren't limited to empty classes; you can define a constructor in your attribute class to capture specific configuration.
Take a routing system, for example. Instead of a giant array mapping URLs to controllers, you can put the route right on the method:
#[Attribute] class Route { public function __construct(public string $path, public string $method = 'GET') {} } class ProductController { #[Route('/products/view', method: 'GET')] public function show() { /* ... */ } #[Route('/products/save', method: 'POST')] public function save() { /* ... */ } }When you instantiate the attribute via
$attribute->newInstance(), PHP returns an actual object of theRouteclass, giving you full access to that$pathand$method. It's a much cleaner way to organize metadata than using docblock comments (which are just strings that you'd have to parse with regex) or massive configuration files.
📋 Practical Task
Building a Reflection-Based Property Validator
Your task is to create a basic validation system using Attributes. Instead of manually checking every property in a class, you will build a validator that reads attributes to determine which properties are mandatory.
Requirements:
- Create an attribute class called
#[Required]. - Create a
UserRegistrationclass with several properties (e.g.,username,email,bio). Markusernameandemailwith the#[Required]attribute, but leavebiounmarked. - Write a
Validatorclass with a methodvalidate(object $obj). - Inside the
validatemethod, useReflectionClassandReflectionProperty::getAttributes()to find all properties marked#[Required]. - If a property marked
#[Required]isnullor an empty string, the validator should throw anExceptionnaming the missing field.
Test your code: Try instantiating UserRegistration without an email and ensure your validator catches it!
There are no comments for now.