Make objects initially inconsistent, yet eventually immutable
MIT License
Warning: I didn't use this library "in the wild" - please let me know if it works in your situation
Just run:
composer require matthiasnoback/convenient-immutability
I've often encountered the following situation (in particular when working with command objects).
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:
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.)
The MIT License (MIT). Please see License File for more information.