Cosa Sono gli Attributes?
Gli Attributes (introdotti in PHP 8) permettono di aggiungere metadata strutturati a classi, metodi, proprietà e parametri.
Creare un Attribute
<?php
#[\Attribute]
class Route
{
public function __construct(
public string $path,
public string $method = 'GET',
public array $middleware = []
) {}
}
// Utilizzo
class UserController
{
#[Route('/users', 'GET')]
public function index() {}
#[Route('/users/{id}', 'GET')]
public function show(int $id) {}
#[Route('/users', 'POST', ['auth', 'admin'])]
public function store() {}
}
?>
Leggere gli Attributes
<?php
// Reflection per leggere attributes
$reflection = new \ReflectionClass(UserController::class);
foreach ($reflection->getMethods() as $method) {
$attributes = $method->getAttributes(Route::class);
foreach ($attributes as $attribute) {
$route = $attribute->newInstance();
echo "Route: {$route->method} {$route->path}\n";
echo "Middleware: " . implode(', ', $route->middleware) . "\n";
}
}
?>
Gli Attributes sono perfetti per routing, validation, caching e dependency injection!