fratily / attribute-loader
1.0.0
2022-01-31 15:17 UTC
Requires
- php: ^8.0
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpstan/phpstan-phpunit: ^1.0
- phpstan/phpstan-strict-rules: ^1.1
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.6
README
Attribute Loader wraps ReflectionAttribute.
How to use
General
#[Attribute] class FooAttribute {} #[FooAttribute] function target_function(): void {} $loader = new Fratily\AttributeLoader\AttributeLoader(FooAttribute::class); $attributes = $loader->load(new ReflectionFunction('target_function')); var_dump($attributes[0]); // object(FooAttribute)
Custom instance builder
AttributeLoader::load()
uses ReflectionAttribute::newInstance()
by default to instantiate.
However, if you want to interrupt the instantiation process for some reason, you can do the following:
#[Attribute] class FooAttribute {} #[FooAttribute(name: 'abc')] function target_function(int $number): void {} $loader = new Fratily\AttributeLoader\AttributeLoader( FooAttribute::class, function (ReflectionAttribute $attr) { var_dump($attr->getArguments()); // array('name' => 'abc') // do something ... // ex: trigger event / customize attribute arguments ... // MUST return an instance of $attr->getName(). // MUST not return a subclass of $attr->getName(). return new FooAttribute(); } ); $attributes = $loader->load(new ReflectionFunction('target_function')); var_dump($attributes[0]); // object(FooAttribute)