#Bag - Immutable Value objects for Laravel
1 messages · Page 1 of 1 (latest)
@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.
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.
I didn't address the second part of this, yes, you can make the properties readonly, but there's no built-in way to cleanly mutate that value, and the value itself isn't readonly, and it's just not built around that being a core-concept.