https://github.com/jclaveau/php-immutable-trait
A trait providing togglable immutability to whatever you want
https://github.com/jclaveau/php-immutable-trait
Last synced: 2 months ago
JSON representation
A trait providing togglable immutability to whatever you want
- Host: GitHub
- URL: https://github.com/jclaveau/php-immutable-trait
- Owner: jclaveau
- License: mit
- Created: 2018-11-04T17:06:15.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2018-11-07T17:44:22.000Z (over 6 years ago)
- Last Synced: 2025-02-13T19:41:18.426Z (4 months ago)
- Language: PHP
- Size: 17.6 KB
- Stars: 3
- Watchers: 5
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Immutable Trait
This trait makes it super easy to turn an instance immutable or mutable.## Quality
[](https://travis-ci.org/jclaveau/php-immutable-trait)
[](https://codecov.io/gh/jclaveau/php-immutable-trait)
[](https://github.com/jclaveau/php-immutable-trait/issues)
[](http://hits.dwyl.com/jclaveau/php-immutable-trait)## Installation
php-immutable-trait is installable via [Composer](http://getcomposer.org)composer require jclaveau/php-immutable-trait
## Usage
```php
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?