承接 bakabot/attribute 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

bakabot/attribute

最新稳定版本:2.0.1

Composer 安装命令:

composer require bakabot/attribute

包简介

Provides accessors to single-value PHP Attributes.

README 文档

README

Provides accessors to single-value PHP Attributes.

Installation

composer require bakabot/attribute

Flavors

For ease of use the library provides three identical way of accessing attribute values:

namespace Bakabot\Attribute;

// functions
attr(string|object $class, string $attribute, mixed $default = null): mixed;
getValue(string|object $class, string $attribute, mixed $default = null): mixed;

// public static method
AttributeValueGetter::getAttributeValue(string|object $class, string $attribute, mixed $default = null): mixed;

Usage

Works on both instances and class names:

use function Bakabot\Attribute\getValue;

#[Attribute]
class SomeAttribute
{
    public function __construct(private string $value) {}
}

#[SomeAttribute('foo')]
class MyClass {}

$value = getValue(MyClass::class, 'SomeAttribute'); // "foo"
$value = getValue(new MyClass(), 'SomeAttribute'); // "foo"

Throws a MissingAttributeException if the attribute is not set:

getValue(MyClass::class, 'UnknownAttribute');
// uncaught Bakabot\Attribute\Exception\MissingAttributeException

Unless you provide a default value as a third argument:

getValue(MyClass::class, 'UnknownAttribute', 'foo'); // "foo"
getValue(MyClass::class, 'UnknownAttribute', 'bar'); // "bar"
getValue(MyClass::class, 'UnknownAttribute', 'baz'); // "baz"

For heavy lifting or lazy evaluation, a default value can be any callable, in which case its resulting value will be cached.

getValue(MyClass::class, 'UnknownAttribute', fn () => 'bar'); // "bar"
getValue(MyClass::class, 'UnknownAttribute'); // still "bar"

If the attribute is repeatable, it'll return an array of that attribute's values:

use function Bakabot\Attribute\getValue;

#[Attribute(Attribute::IS_REPEATABLE)]
final class RepeatableAttribute
{
    public function __construct(private string $value) {}
}

#[RepeatableAttribute('foo')]
#[RepeatableAttribute('bar')]
class MyClass {}

$value = getValue(MyClass::class, 'RepeatableAttribute'); // ["foo", "bar"]

统计信息

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

GitHub 信息

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

其他信息

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