jclaveau / php-immutable-trait
A trait to implement easily (im)mutable objects
1.0.1
2018-11-04 19:14 UTC
Requires
- php: >=5.6.0
Requires (Dev)
- dusank/knapsack: ^10.0
- jclaveau/phpunit-profile-asserts: ^1.0
- jclaveau/phpunit-testlistener-xhprof: dev-master
- jclaveau/xhprof: dev-master
- phpunit/phpunit: 5.*
This package is auto-updated.
Last update: 2024-11-08 08:30:20 UTC
README
This trait makes it super easy to turn an instance immutable or mutable.
Quality
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?