tiny-blocks / immutable-object
Provides immutable behavior for objects.
Installs: 5 383
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.2
Requires (Dev)
- infection/infection: ^0.29
- phpmd/phpmd: ^2.15
- phpstan/phpstan: ^1
- phpunit/phpunit: ^11
- squizlabs/php_codesniffer: ^3.10
README
Overview
The Immutable Object library ensures that objects implementing it remain immutable after initialization. Once created, the state of the object cannot be modified. Any attempt to change properties or collection elements will throw an exception.
Installation
composer require tiny-blocks/immutable-object
How to use
The library provides the Immutable
interface and the Immutability
trait to guarantee immutability. These components
prevent properties and collections from being modified or unset.
Concrete implementation
By implementing the Immutable
interface and using the Immutability
trait, you can ensure that object properties and
elements in collections are immutable.
<?php namespace Example; use TinyBlocks\Immutable\Immutable; use TinyBlocks\Immutable\Immutability; final class Order implements Immutable { use Immutability; public function __construct(public int $id, public Products $products) { } }
Handling property immutability
The Immutability trait also prevents modifications to properties of an object. Trying to modify a property after the object is initialized will throw an exception.
$order = new Order(id: 1, products: new Products(array: ['item1', 'item2']); $order->id = 2; # Throws an exception unset($order->id); # Throws an exception
Handling collection immutability
The Immutability
trait also prevents the modification of collection elements (e.g., arrays). Trying to modify or
remove an element will throw an exception.
$order = new Order(id: 1, products: new Products(array: ['item1', 'item2']); $order->items[0] = 'item3'; # Throws an exception unset($order->items[0]); # Throws an exception
License
Immutable Object is licensed under MIT.
Contributing
Please follow the contributing guidelines to contribute to the project.