jclaveau/php-immutable-trait

A trait to implement easily (im)mutable objects

1.0.1 2018-11-04 19:14 UTC

This package is auto-updated.

Last update: 2024-12-08 08:43:47 UTC


README

This trait makes it super easy to turn an instance immutable or mutable.

Quality

Build Status codecov contributions welcome Viewed

Installation

php-immutable-trait is installable via Composer

composer require jclaveau/php-immutable-trait

Usage

class ImmutableObject
{
    use Immutable;
    // use SwitchableMutability; // This traits provides becomesMutable() and becomesImmutable()

    protected $property;

    public function setProperty($value)
    {
        // Just add these lines at the really beginning of methods supporting
        // immutability (setters mostly)
        if ($this->callOnCloneIfImmutable($result))
            return $result;

        // $this is now the new instance if it's immutable
        $this->property = $value;
        return $this;
    }

    public function getProperty()
    {
        return $this->property;
    }
}


$instance = new ImmutableObject;
$instance2 = $instance->setProperty('new value');

var_dump( $instance->getProperty() ); => null
var_dump( $instance2->getProperty() ); => 'new value'

TODO

  • Profiles
  • PHP 7
  • Support immutability for private / protected methods? Should the dev handle it? Should we provide a simple protected API for it?