#Bag - Immutable Value objects for Laravel

1 messages · Page 1 of 1 (latest)

spring cypress
#

Do you do anything around the fact Collections aren't 100% immutable (there are mutable methods e.g. push)? Just considering your big difference vs laravel data is immutability.

If not, I guess apart from the framework agnostic what is the difference here vs laravel-data as you can make all your properties readonly if needed.

stiff parrot
#

@spring cypress great question, it's unfortunately not possible to have true immutability in PHP because even in readonly properties of arrays or objects, the underlying data can be modified. I don't use Collection for the underlying storage, except for collections of value objects. Most collection methods returns a new collection rather than modifying the original anyway, so I think it's pretty OK. I could extend it and prevent offsetSet() and __set() I guess.

stiff parrot
#

OK, I added a custom Collection class that disallows all methods that modify the original collection unless it returned the original collection in the first place, then I clone it and return that one modified instead.

stiff parrot