amondar-libs/class-attributes 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

amondar-libs/class-attributes

Composer 安装命令:

composer require amondar-libs/class-attributes

包简介

PHP class attributes workflow for package development.

README 文档

README

This package provides a small, framework-friendly toolkit to work with native PHP 8 attributes on your classes and methods. It leverages spatie/php-structure-discoverer for fast and efficient attribute discovery.

What you get:

  • Simple fluent API to read class, method, property, constant, and parameter attributes
  • Support for repeatable attributes and inheritance lookups
  • Filtering helpers: onClass(), onMethods(), onProperties(), onConstants(), onParameters()
  • Optional caching support for performance in production

Installation:

composer require amondar-libs/class-attributes

Contents:

Attributes usage

Below are quick, copy-pasteable examples showing how to declare attributes and how to read them using this package.

The package works with native PHP attributes (PHP >= 8.3). It provides a fluent Amondar\ClassAttributes\Parse helper.

1) Define your attributes

Create attribute classes using native PHP Attribute metadata.

use Attribute;

#[Attribute(Attribute::TARGET_CLASS)]
class ClassAttribute
{
    public function __construct(public array $someData) {}
}

#[Attribute(Attribute::TARGET_METHOD)]
class MethodAttribute
{
    public function __construct(public string $description) {}
}

#[Attribute(Attribute::TARGET_ALL)]
class TagAttribute
{
    public function __construct(public string $description) {}
}

2) Annotate your classes/methods

#[ClassAttribute(['someData' => 'someValue'])]
class Example
{
    #[TagAttribute('MyConst')]
    public const MY_CONST = 'my-const';

    #[TagAttribute('isOk')]
    public bool $isOk = true;

    #[MethodAttribute('First method description')]
    public function firstMethod() {}

    #[MethodAttribute('Second method description')]
    public function secondMethod() {}
}

3) Read attributes: Parse helper

The get() method returns a Collection of Discovered objects. Each Discovered instance contains:

  • name — the name of the target (class name, method name, property name, etc.)
  • parent — the parent/declaring class name (FCQN)
  • attribute — the attribute instance
  • target — a Target enum case (onClass, method, property, constant, parameter)
use Amondar\ClassAttributes\Parse;

// Get all discovered attributes on a class (class-level, methods, properties, constants)
$results = Parse::attribute(TagAttribute::class)
    ->on(Example::class)
    ->get();

// $results is a Collection of Discovered instances
foreach ($results as $discovered) {
    echo $discovered->name;              // e.g. 'MY_CONST', 'isOk', 'firstMethod'
    echo $discovered->target->value;     // e.g. 'constant', 'property', 'method'
    echo $discovered->attribute->description; // e.g. 'MyConst'
}

4) Filter by target

Use dedicated filter methods to narrow results to a specific target type:

// Only class-level attributes
$classAttrs = Parse::attribute(ClassAttribute::class)
    ->on(Example::class)
    ->onClass();

// Only method attributes
$methodAttrs = Parse::attribute(MethodAttribute::class)
    ->on(Example::class)
    ->onMethods();

// Only property attributes
$propAttrs = Parse::attribute(TagAttribute::class)
    ->on(Example::class)
    ->onProperties();

// Only constant attributes
$constAttrs = Parse::attribute(TagAttribute::class)
    ->on(Example::class)
    ->onConstants();

// Only parameter attributes
$paramAttrs = Parse::attribute(RequestAttribute::class)
    ->on(Example::class)
    ->onParameters();

5) Inheritance lookup

Include parent class attributes in the search using ascend():

$results = Parse::attribute(TagAttribute::class)
    ->on(ChildOfExample::class)
    ->ascend()
    ->get();

That will include attributes from Example class and all its parents. Can be useful for resolving repeatable attributes, for example, when a child can add some new functionality.

Attribute class usage

Under the hood, the Parse facade delegates to Amondar\ClassAttributes\Support\Attribute — a lower-level, reflection-based class you can use directly for fine-grained control.

Creating an instance

Use the static for() factory, passing either a class-string or a DiscoveredAttribute instance:

use Amondar\ClassAttributes\Support\Attribute;

$attr = Attribute::for(TagAttribute::class);

Checking if an attribute exists

The existsOn() method returns true if the attribute is present anywhere on the class (class-level, methods, properties, constants, or parameters):

$attr->existsOn(Example::class); // true / false

Finding all attribute usages on a class

findOn() returns an array of Discovered objects for every occurrence of the attribute on the given class:

$results = $attr->findOn(Example::class);
// array<Discovered>

Targeted lookups

Each method accepts a class-string, an object, or a ReflectionClass instance. They return an array of Discovered objects (or bool when the $exist flag is true):

// Class-level attributes only
$attr->on(Example::class);

// Method attributes only (optionally include parameter attributes)
$attr->onMethods(Example::class, includeParameters: true);

// Property attributes only
$attr->onProperties(Example::class);

// Constant attributes only
$attr->onConstants(Example::class);

// Parameter attributes only
$attr->onParameters(Example::class);

You can also pass a visibility filter using PHP's ReflectionMethod/ReflectionProperty filter constants:

$attr->onMethods(Example::class, filter: ReflectionMethod::IS_PUBLIC);
$attr->onProperties(Example::class, filter: ReflectionProperty::IS_PUBLIC);
$attr->onConstants(Example::class, filter: ReflectionClassConstant::IS_PUBLIC);

Inheritance lookup

Just like the Parse helper, you can include parent class attributes with ascend():

$attr = Attribute::for(TagAttribute::class)->ascend();

$results = $attr->findOn(ChildOfExample::class);
// Includes attributes from ChildOfExample and all its parents

Batch Discovery

You can discover all classes using a specific attribute within given directories.

use Amondar\ClassAttributes\Parse;

$parser = Parse::attribute(ClassAttribute::class);

// Find all classes that use this attribute
$usages = $parser->findUsages(__DIR__ . '/src');
// Returns Collection of \Spatie\StructureDiscoverer\Data\DiscoveredClass

// Discover and parse all attributes for classes in directories
$all = $parser->in(__DIR__ . '/src', __DIR__ . '/tests');
// Returns Collection<class-string, Collection<string, Collection<int, Discovered>>>

Caching

For production environments, you can enable caching to avoid repeated reflection and file scanning.

The package uses spatie/php-structure-discoverer caching mechanism. You can use any driver that implements Spatie\StructureDiscoverer\Cache\DiscoverCacheDriver.

use Amondar\ClassAttributes\Parse;
use Spatie\StructureDiscoverer\Cache\LaravelDiscoverCacheDriver;

$parser = Parse::attribute(ClassAttribute::class)
    ->withCache(new LaravelDiscoverCacheDriver('my-cache-key'));

// Subsequent calls will be cached
$result = $parser->on(Example::class)->get();

Note: LaravelDiscoverCacheDriver is just one example. You can use any driver supported by spatie/php-structure-discoverer official docs. Current package ships with Amondar\\ClassAttributes\\Laravel\\AttributeCacheDriver out of the box.

License

This library is open-sourced software licensed under the MIT license. See LICENSE.md.

amondar-libs/class-attributes 适用场景与选型建议

amondar-libs/class-attributes 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 62 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 10 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 amondar-libs/class-attributes 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 amondar-libs/class-attributes 我们能提供哪些服务?
定制开发 / 二次开发

基于 amondar-libs/class-attributes 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 62
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 18
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-27