Lab 07: PHP Attributes
Step 1: Declaring a Custom Attribute
<?php
// Restrict to class and method targets
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class Route {
public function __construct(
public readonly string $path,
public readonly string $method = 'GET'
) {}
}
#[Route('/users')]
class UserController {
#[Route('/users/{id}', 'GET')]
public function show(int $id): void {}
#[Route('/users', 'POST')]
public function create(): void {}
#[Route('/users/{id}', 'DELETE')]
public function delete(int $id): void {}
}
// Read via Reflection
$rc = new ReflectionClass(UserController::class);
foreach ($rc->getAttributes(Route::class) as $attr) {
$r = $attr->newInstance();
echo "Controller: {$r->method} {$r->path}\n";
}
foreach ($rc->getMethods() as $method) {
foreach ($method->getAttributes(Route::class) as $attr) {
$r = $attr->newInstance();
echo "{$r->method} {$r->path} → {$method->getName()}()\n";
}
}Step 2: Attribute Target Flags
Step 3: Repeatable Attributes
Step 4: Built-in PHP Attributes
Step 5: Validation Attribute Pattern
Step 6: Event Listener Attribute
Step 7: Parameter Attributes & Type Checking
Step 8: Capstone — Mini Router with Attribute-Based Routing
Summary
Feature
Syntax
PHP Version
Last updated
