Immutable encapsulations

Sometimes it's necessary to prevent changing data of an encapsulation. Immutable encapsulations must be initialized with data in their constructor. Afterwards data cannot be changed.

Immutable ArrayEncapsulation

Immutable ArrayEncapsulations can hold any data without restriction.

use Dustin\Encapsulation\ImmutableEncapsulation;

$encapsulation = new ImmutableEncapsulation([
    'foo' => 'bar',
    'hello' => 'world'
]);

$encapsulation->set('field', 'value'); // Will throw an exception

Immutability in your own encapsulation

Each encapsulation class you create on your own can be immutable regardless wether it's an ArrayEncapsulation or a PropertyEncapsulation or something else.

use Dustin\Encapsulation\PropertyEncapsulation;
use Dustin\Encapsulation\ImmutableTrait;

class MyEncapsulation extends PropertyEncapsulation {
    
    use ImmutableTrait;
    
    protected $foo = null;
    
    protected $bar = null;
}

$encapsulation = new MyEncapsulation(['foo' => 'foo']);

$encapsulation->set('bar', 'bar'); // Will throw an exception

Each encapsulation inheriting from AbstractEncapsulation can be checked about their mutability:

use Dustin\Encapsulation\Encapsulation;

$encapsulation = new Encapsulation(['foo' => 'foo']);
$myEncapsulation = new MyEncapsulation(['foo' => 'foo', 'bar' => 'bar']);

$encapsulation->isMutable(); // Returns true
$myEncapsulation->isMutable(); // Returns false

Immutable containers

There is also a class of an immutable container which prevents changing it's elements.

use Dustin\Encapsulation\ImmutableContainer;

$container = new ImmutableContainer(['foo', 'bar']);

$container->add('Hello world'); // Will throw an exception

Last updated