atomino / util-attr
PHP 属性处理器
1.0
2022-03-17 11:53 UTC
README
轻松使用 PHP8 属性!
get(\ReflectionClass|\ReflectionMethod|string $reflection, string|null $method = null):static|null all(\ReflectionClass|\ReflectionMethod|string $reflection, string|null $method = null):static|null collect(\ReflectionClass|\ReflectionMethod ...$reflections):static[]
创建属性
按照常规创建 Attribute
类,只需从 \Atomino\Neutrons\Attr
类扩展即可。
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)] class MyAttr extends \Atomino\Neutrons\Attr { public function __construct(public string $name){...} } #[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)] class MyRepeatableAttr extends \Atomino\Neutrons\Attr { public function __construct(public string $name){...} }
将属性添加到类或方法中
#[MyAttr("my awesome class")] #[MyRepeatableAttr("my awesome class")] class MyClass { #[MyAttr("my awesome method")] #[MyRepeatableAttr("my awesome method")] #[MyRepeatableAttr("my awesome method two")] public function myMethod(){...} }
查询单个属性(get
)
get(\ReflectionClass|\ReflectionMethod|string $reflection, string|null $method = null):static|null
返回值将是一个属性实例或 null
基于反射的查询
然后根据类或方法的反射获取属性。IDE 将知道您请求的属性类型,代码补全将工作正常。
$classRef = new ReflectionClass(MyClass::class); $attr = MyAttr::get($classRef); echo $attr->name; $methodRef = $classRef->getMethod("myMethod"); $attr = MyAttr::get($methodRef); echo $attr->name;
基于名称的查询
如果您不想使用反射,可以通过类(和方法的)名称获取属性。
$attr = MyAttr::get(MyClass::class); echo $attr->name; $attr = MyAttr::get(MyClass::class, "myMethod"); echo $attr->name;
查询可重复属性(all
)
all(\ReflectionClass|\ReflectionMethod|string $reflection, string|null $method = null):static|null
返回值将是一个包含属性实例的数组
基于反射的查询
然后根据类或方法的反射获取属性数组。IDE 将知道您请求的属性类型,代码补全将工作正常。
$classRef = new ReflectionClass(MyClass::class); $attrs = MyRepeatableAttr::all($classRef); foreach ($attrs as $attr) echo $attr->name; $methodRef = $classRef->getMethod("myMethod"); $attrs = MyRepeatableAttr::all($methodRef); foreach ($attrs as $attr) echo $attr->name;
基于名称的查询
如果您不想使用反射,可以通过类(和方法的)名称获取属性。
$attrss = MyRepeatableAttr::all(MyClass::class); foreach ($attrs as $attr) echo $attr->name; $attrs = MyRepeatableAttr::all(MyClass::class, "myMethod"); foreach ($attrs as $attr) echo $attr->name;
查询多个反射的属性(collect
)
collect(\ReflectionClass|\ReflectionMethod ...$reflections):static[]
返回值将是一个包含属性实例的数组
如果您想批量检索多个类或方法的属性,可以使用 collect
方法。
$classRef = new ReflectionClass(MyClass::class); $methodRefs = $classRef->getMethods(); $attrs = MyAttr::collect($classRef, ...$methodRefs); foreach ($attrs as $attr) echo $attr->name;