Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

Explain Reflection vs. Attributes in PHP 8.x and how to build high-performance metadata routers.

Real-World Scenario / Incident Description

Migrating a custom framework from legacy docblock annotations (`@Route("/api/users")`) to native PHP 8 Attributes (`#[Route("/api/users")]`).

401 views • Updated 1 month ago

Creating & Reading Native Attributes

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
class Route
{
    public function __construct(
        public string $path,
        public string $method = 'GET'
    ) {}
}

class UserController
{
    #[Route('/api/v1/users', method: 'GET')]
    public function list(): JsonResponse { ... }
}

// Reading via Reflection
$reflection = new ReflectionMethod(UserController::class, 'list');
$attributes = $reflection->getAttributes(Route::class);
foreach ($attributes as $attr) {
    $routeInstance = $attr->newInstance();
    echo $routeInstance->path; // '/api/v1/users'
}

Native attributes are parsed at compile time, eliminating regex docblock string parsing.

Related Concepts: #Attributes #Reflection #Metadata #Routing