spatie/php-attribute-reader
Lightweight PHP 8+ utility to read native attributes from classes, methods, properties, and parameters using reflection. Designed for simple, fast attribute discovery in frameworks and libraries, with an API that fits common annotation-style workflows.
Start by installing the package via Composer:
composer require spatie/php-attribute-reader
Then, create a simple attribute-driven class to test basic functionality. For example, define an attribute like #[Route('/users')] on a class method, and use the AttributeReader class to retrieve it:
use Spatie\AttributeReader\AttributeReader;
$reader = new AttributeReader();
$methods = $reader->getMethods(new MyClass());
$routes = $reader->getAttributeInstances($methods['index'], Route::class);
First use case: reading route attributes from controller methods to build a routing table at runtime — ideal for lightweight frameworks or middleware builders.
getAttributeInstances() to retrieve all attribute instances of a given class from a reflection target (class, method, property, parameter). Useful for tag-based configurations (e.g., #[Cacheable('hourly')], #[Loggable('debug')]).Route::class) or a string name ('Route') to filter. For multi-attribute scenarios (e.g., a method with #[Route('/api'), #[Authorize('admin')]), chain filters or retrieve all at once.useAttributeAnnotations() for fallback reading of docblock tags (e.g., @Route("/legacy")), easing migration from docblock-based tools to native attributes.AttributeReader into services like validation validators, command handlers, or event dispatchers to drive behavior declaratively (e.g., #[Validates(type: User::class)]).readonly and you need to override values (e.g., in tests), instantiate manually or use getAttributeInstances(..., $useConstructor: false) if supported.$reader->useAttributeAnnotations(true)) — it’s slower and may cause false positives if docblocks are noisy.AttributeReader to add custom behavior (e.g., logging all reads), or wrap it in a domain-specific facade (e.g., RouteReader::fromClass(RequestHandler::class)).How can I help you explore Laravel packages today?