Update April 25th, 2016: I don’t use Value Objects in Laravel anymore. Here’s why.
One idea of Value Objects is to restrict what a programmer can do within the model. For example, an EmailAddress value object cannot be set to an invalid email address.
The advantage is: Validation and consistency of the domain model.
With Laravel however, there are a few things to think about and it took me a while to figure out a good solution.
- Use a Mutator to enforce the type of a Value Object
- Store your Value Object as native value in your Eloquent model
- Use an Accessor to create a Value Object from the native value
__toString()in your Value Object to allow
- Use the
JsonSerializableinterface to allow
- Plus: Do all of this automatically without Mutators and Accessors