judahnator/public-accessor-attribute
Composer 安装命令:
composer require judahnator/public-accessor-attribute
包简介
A trait and attribute that provides read-only access to protected class properties.
README 文档
README
I know it's a mouthful, words are hard, and naming things is harder.
The Gist
With the goal of having read-only (write-once?) properties, you may need to write things like this from time to time:
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();
What if I told you there was a better way?
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')
Yeah, I know it's not pretty, sue me.
Basically, any protected or public (but why would you do this) property with the handy #[ReadOnly] attribute slapped on will be accessible from the public getCamelCaseVariableNameAttribute() method. Alternatively, you can use the getAttribute() method and pass in the attribute name directly.
统计信息
- 总下载量: 10
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-01-27