PHP 属性和反射的更清晰的 API。

1.0.0 2024-09-27 13:22 UTC

This package is auto-updated.

Last update: 2024-09-28 11:59:11 UTC


README

Reflect

需求

PHP 8.1 或更高版本

安装

composer require princejohnsantillan/reflect

示例

之前

enum Plan: string{
    case FREE = 'free';
    case HOBBY = 'hobby';
    case PRO = 'professional';
    case TEAM = 'team';
    case ENTERPRISE = 'enterprise';
    
    public function price(): int {
        return match($this){
            static::FREE => 0,
            static::HOBBY => 10,
            static::PRO => 20,
            static::TEAM => 50,
            static::ENTERPRISE = 200
        };
    }
    
    public function color(): string {
        return match($this){
            static::FREE => 'yellow',
            static::HOBBY => 'orange',
            static::PRO => 'blue',
            static::TEAM => 'silver',
            static::ENTERPRISE = 'gold'
        };
    }
}

之后

use PrinceJohn\Reflect\Traits\HasEnumTarget;

#[\Attribute]
class Price{
    use HasEnumTarget;
    
    public function __construct(public int $price) {}
}
use PrinceJohn\Reflect\Traits\HasEnumTarget;

#[\Attribute]
class Color{
    use HasEnumTarget;
    
    public function __construct(public string $color) {}
}
use PrinceJohn\Reflect\Enum\Reflect;

enum Plan: string{
    #[Price(0)]
    #[Color('yellow')]
    case FREE = 'free';
    
    #[Price(10)]
    #[Color('orange')]
    case HOBBY = 'hobby';
    
    #[Price(20)]
    #[Color('blue')]
    case PRO = 'professional';
    
    #[Price(50)]
    #[Color('silver')]
    case TEAM = 'team';
    
    #[Price(200)]
    #[Color('gold')]
    case ENTERPRISE = 'enterprise';
    
    public function price(): int {
        // Demonstrating usage via the Reflect class        
        return Reflect::on($this)
            ->getAttributeInstance(Price::class)
            ->price;            
    }
    
    public function color(): string {
        // Demonstrating usage via the HasEnumTarget trait
        return Color::onEnum($this)->color;
    }
}

注意

或者,只需返回属性类,这样你可以使用更多的功能。