authanram/attributes

PHP8 属性的低级使用

v0.1.0 2022-02-01 16:01 UTC

This package is auto-updated.

Last update: 2024-09-24 01:58:28 UTC


README

PHP8带来的属性简单使用。

安装

composer require authanram/attributes

使用方法

为任何目的、类型转换、映射等创建属性类。

<?php

namespace AwesomeProject\Attributes;

#[Attribute(Attribute::TARGET_PROPERTY)]
AwesomeAttribute
{
    /**
     * @param mixed ...$args // ['whatever', 'data']
     */
    public funtion __construct(mixed ...$args)
    {}
    
    /**
     * @param object $context   // Instance of AwesomeProject\AwesomeClass
     * @param string $name      // 'foo' (The name of the property the attribute belongs to)
     * @param mixed ...$args    // ['your', 'args']
     * 
     * @return void
     */
    public function handle(object $context, string $name, mixed ...$args)
    {
    }
    
    /**
     * @param mixed $old // 'qux'
     * 
     * @return string
     */
    public function value(mixed $old): string
    {
        return 'bar';
    }
}

使用您的属性(在某个地方)

例如:

<?php

namespace AwesomeProject;

use Authanram\Attributes;

AwesomeClass
{
    #[Attributes\AwesomeAttribute('whatever', 'data')]
    public string $foo = 'qux';
    
    public function __construct()
    {
        new Attributes($this, 'your', 'args');
    }
}

创建一个实例

$instance = new \AwesomeProject\AwesomeClass();

$instance->foo; // 'bar'

一些词汇

方法 handlevalue 只有在存在时才会被调用。这意味着如果构造函数(和参数)以及其中一个方法符合您的需求,另一个方法可以省略。

在底层,将创建属性类的实例,如果存在,将调用方法 handlevalue

方法 value 的返回值将被分配给相应的属性。通过传递给 handle 方法的参数 $context$name,您可以将值手动分配给属性所属的属性,例如 $context->{$name} = 'qux';

总的来说,这应该为您提供了在代码中利用属性的一些低级工具。

测试

vendor/bin/pest