Home

Awesome

Convenient immutability for (some) PHP objects

Warning: I didn't use this library "in the wild" - please let me know if it works in your situation

Build Status Coverage Status Latest Version on Packagist Total Downloads Software License

Installation

Just run:

composer require matthiasnoback/convenient-immutability

Introduction

I've often encountered the following situation (in particular when working with command objects).

  1. I start with a simple object (in fact, a DTO), with just some public properties.
  2. The Symfony Form component copies some values into the object's properties.
  3. I copy some extra data into the object (like a generated UUID).
  4. I then use that object as a command or query message, handing it over to some inner layer of my application.

In other words, I have a class that looks like this:

class OrderSeats
{
    public $id;
    public $userId;
    public $seatNumbers = [];
}

And use it like this:

$form = $this->factory->create(OrderSeatsFormType::class);
$form->submit($request);
$command = $form->getData();
$command->id = Uuid::uuid4();

$commandBus->handle($command);

Then I want it to be impossible to change any field on the (command) object, making it effectively immutable.

The ConvenientImmutability\Immutable trait solves this problem. When your class uses this trait, it:

Why would you do this?

What's the problem with this approach?

Is this bad? I don't think so. As long as you validate the objects (e.g. using the Symfony Validator) and then throw them into your domain layer, which contains the actual safeguards against inconsistent state.

(You can also just use public properties and treat them as "set once, never again" in other parts of your application.)

License

The MIT License (MIT). Please see License File for more information.