codelicia/immutable

This package is abandoned and no longer maintained. No replacement package was suggested.

Enforces immutability on initialized properties of any PHP object

dev-master 2021-07-22 09:48 UTC

This package is not auto-updated.

Last update: 2021-08-04 00:10:38 UTC


README

Build Status

Since the PHP RFC: Readonly properties 2.0 will be available on PHP 8.1 this repository will be archived.

It enforces immutability on initialized properties.

Immutable properties can be really handful to avoid getter/setter boiler-plate or just enforce immutability for specific objects.

We see it as specially useful for the following use cases: VOs, DTOs, Commands, Events and ViewModels.

Installation

$ composer require codelicia/immutable

Usage

Enable immutability on your classes just by plugging the ImmutableProperties trait on it.

final class User
{
    use \Codelicia\ImmutableProperties;

    public string $name;
    public int $age;
}

$user       = new User;
$user->name = "@malukenho";

// this will crash
$user->name = "Throws exception as the property name cannot be reassigned";

We recommend you create a __construct to make the object stay in a valid state right after the instantiation of it, but it is up to you and your necessity.

final class User
{
    use \Codelicia\ImmutableProperties;

    // It is fine to leave the properties visibility as public as the `ImmutableProperties`
    // trait will not allow it to change after it is being initialized in the
    // class constructor
    public string $name;
    public int $age;

    public function __construct(string $name, int $age)
    {
        $this->init(); // The `init()` method must be called here

        $this->name = $name;
        $this->age = $age;
    }
}

Authors