PHP Attributes (PHP 8.0+)
#[\Attribute]
class Route {
public function __construct(
public string \$path,
public string \$method = 'GET',
) { }
}
class UserController {
#[Route('/users', 'GET')]
public function index(): array {
return [];
}
#[Route('/users', 'POST')]
public function store(): array {
return [];
}
}
Reading Attributes
\$reflection = new ReflectionMethod(
UserController::class, 'index'
);
\$attributes = \$reflection->getAttributes(Route::class);
foreach (\$attributes as \$attribute) {
\$route = \$attribute->newInstance();
echo \$route->path; // /users
}