fratily/attribute-loader

1.0.0 2022-01-31 15:17 UTC

This package is auto-updated.

Last update: 2024-09-29 05:57:03 UTC


README

Attribute Loader 包装了 ReflectionAttribute

如何使用

常规

#[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)

自定义实例构建器

AttributeLoader::load() 默认使用 ReflectionAttribute::newInstance() 来实例化。但是,如果您出于某种原因想要中断实例化过程,您可以执行以下操作

#[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)