judahnator/public-accessor-attribute

A trait and attribute that provides read-only access to protected class properties.

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

This package is not auto-updated.

Last update: 2024-05-03 07:23:21 UTC


README

pipeline status coverage report

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.