ryangjchandler/computed-properties

A small package to add computed properties to any PHP class.

v0.2.0 2021-09-03 14:08 UTC

This package is auto-updated.

Last update: 2024-03-29 04:45:59 UTC


README

GitHub Workflow Status (main) Total Downloads Latest Version License

This package provides a trait and attribute that can provide computed property support.

Installation

This package can be installed via Composer:

composer require ryangjchandler/computed-properties

Usage

Begin by adding the RyanChandler\Computed\Traits\WithComputedProperties trait to your class:

use RyanChandler\Computed\Traits\WithComputedProperties;

class Person
{
    use WithComputedProperties;

    public function getNameProperty()
    {
        return 'Ryan';
    }
}

You can then define a method using the get[name]Property naming conventions, where [name] is a pascal-cased version of your desired property name.

In the example above, we will be able to access the property name on the object.

$person = new Person;

echo $person->name; // 'Ryan'

Using Attributes

This package also provides a Computed attribute that allows you to use your own method names.

use RyanChandler\Computed\Traits\WithComputedProperties;
use RyanChandler\Computed\Attributes\Computed;

class Person
{
    use WithComputedProperties;

    public $firstName = 'Ryan';

    public $lastName = 'Chandler';

    #[Computed]
    public function fullName()
    {
        return $this->firstName . ' ' . $this->lastName;
    }
}

By default, Computed will let you access a property using the method name. In the example above, the property will be fullName.

$person = new Person;

echo $person->fullName; // 'Ryan Chandler'

If you would like to change the name of the computed property, you can pass a string to the attribute.

use RyanChandler\Computed\Traits\WithComputedProperties;
use RyanChandler\Computed\Attributes\Computed;

class Person
{
    use WithComputedProperties;

    public $firstName = 'Ryan';

    public $lastName = 'Chandler';

    #[Computed("name")]
    public function fullName()
    {
        return $this->firstName . ' ' . $this->lastName;
    }
}

You can now access the name property, which will run the Person::fullName() method.

$person = new Person;

echo $person->name; // 'Ryan Chandler'

Memoization

If you would like to only generate the value for a computed property once per request, you can add the RyanChandler\Computed\Attributes\Once attribute to your method.

use RyanChandler\Computed\Traits\WithComputedProperties;
use RyanChandler\Computed\Attributes\Once;

class Person
{
    use WithComputedProperties;

    #[Once]
    public function getRandProperty()
    {
        return rand(1, 10000);
    }
}

The random number will only be generated once per request. This is useful for expensive computations.