judahnator/public-accessor-attribute

一个特性和属性,提供对受保护类属性的只读访问。

v1.0.0 2021-01-27 10:21 UTC

This package is not auto-updated.

Last update: 2024-09-20 09:23:33 UTC


README

pipeline status coverage report

我知道这听起来很复杂,单词很难,而且命名事物更难。

要点

目标是拥有只读(一次写入?)属性,你有时可能需要编写如下内容

class foo {
    public function __construct(
        protected string $foo = 'bar',
        protected string $myVar = 'baz',
    ) {}
    
    public  function getFooAttribute(): string {
        return $this->foo;
    }
    
    public function getMyVarAttribute(): string {
        return $this->myVar;
    }
}

$class = new foo();
$class->getFooAttribute();
$class->getMyVarAttribute();

如果我告诉你有更好的方法呢?

use judahnator\PublicAccessorAttribute\HasReadonlyProperties;
use judahnator\PublicAccessorAttribute\ReadOnly;
class foo {
    use HasReadonlyProperties;
    public function __construct(
        #[ReadOnly] protected string $foo =  'bar',
        #[ReadOnly] protected string $myVar =  'bar',
    ) {}
}

$class = new foo();
$class->getFooAttribute(); // or $class->getAttribute('foo')
$class->getMyVarAttribute(); // or $class->getAttribute('myVar')

是的,我知道这看起来不怎么样,起诉我也行。

基本上,任何带有方便的 #[ReadOnly] 属性的受保护或公共(但你为什么要这样做)属性,都可以通过公共的 getCamelCaseVariableNameAttribute() 方法进行访问。或者,你可以使用 getAttribute() 方法并直接传递属性名称。