bfg / attributes
专为与 PHP 8 属性类协同工作而设计
1.2.5
2023-11-23 16:28 UTC
Requires
- php: >=8.0.0
README
安装
composer require bfg/attributes
描述
专为与 PHP 8 属性协同工作而设计
关于概念
该包的概念是在类中查找属性并执行它们。
在哪里可以使用它?
当我们将 PHP 属性用作指向某些动作的指针时。
由于此过程的执行可能会威胁到时间,因此重要的一点是不要在用户过程的总体流中运行此过程。
在属性上调用事件
为了查找属性,我们需要指定将搜索哪个属性,默认情况下,该包搜索除项目中的文件夹 public
、resources
、storage
、runtimes
、database
之外的所有地方,或者您可以手动指定在哪个文件夹中查找属性。
考虑对方法的全局属性搜索
use Bfg\Attributes\Items\AttributeClassItem; use Bfg\Attributes\Items\AttributeConstantItem; use Bfg\Attributes\Items\AttributeMethodItem; use Bfg\Attributes\Items\AttributePropertyItem; use Bfg\Attributes\Attributes; Attributes::new(MyAttribute::class) ->map(function (AttributePropertyItem|AttributeMethodItem|AttributeClassItem|AttributeConstantItem $item) { // Process with my attribute });
或相同的搜索,但针对特定文件夹
use Bfg\Attributes\Items\AttributeClassItem; use Bfg\Attributes\Attributes; Attributes::new(MyAttribute::class) ->wherePath(app_path()) ->map(function (AttributePropertyItem|AttributeMethodItem|AttributeClassItem|AttributeConstantItem $item) { // Process with my attribute });
或仅查找类属性
Attributes::new(MyAttribute::class) ->wherePath(app_path()) ->whereTargetClass() ->map(function (AttributeClassItem $item) { // Process with my attribute });
或相同的搜索,但针对特定类
use Bfg\Attributes\Items\AttributeMethodItem; use Bfg\Attributes\Attributes; Attributes::new(MyAttribute::class) ->whereClass(MyAnyClassNamespace::class) ->whereTargetMethod() ->map(function (AttributeMethodItem $item) { // Process with my attribute });
或您可以获取所有找到的项目属性
use Bfg\Attributes\Items\AttributePropertyItem; use Bfg\Attributes\Attributes; $collectionOfProperties = Attributes::new(MyAttribute::class) ->wherePath(app_path()) ->whereTargetProperty() ->all(); $property = Attributes::new(MyAttribute::class) ->wherePath(app_path()) ->whereTargetProperty() ->filter(fn (AttributePropertyItem $propertyItem) => $propertyItem) ->first();
或您可以获取所有类
use Bfg\Attributes\Attributes; Attributes::new() ->wherePath(app_path()) ->classes(); // In all directories $collectionOfClasses = Attributes::new()->classes();
支持的属性
该包仅支持类属性,例如:Class
、Method
、Property
、Class constant
,或者它们可以同时存在。
检查常量
\Attribute::TARGET_CLASS
\Attribute::TARGET_METHOD
\Attribute::TARGET_PROPERTY
\Attribute::TARGET_CLASS_CONSTANT
\Attribute::TARGET_ALL
(默认)