Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Matthias Noback:
Objects should be constructed in one go
Jul 17, 2018 @ 14:21:04

In a new post to his site Matthias Noback makes an interesting suggestion about working with objects in PHP: that they should all be made in one, and only one, place.

Consider the following rule: "When you create an object, it should be complete, consistent and valid in one go."

It is derived from the more general principle that it should not be possible for an object to exist in an inconsistent state. I think this is a very important rule, one that will gradually lead everyone from the swamps of those dreaded "anemic" domain models. However, the question still remains: what does all of this mean?

He shares an example of an object (GeoLocation) that can be created with only the latitude value but points out that this leaves it in an invalid state. He updates this example to show a more complete implementation, one that prevents an object with partial setup from happening. He then talks about the aggregation of child entities and a "paper" metaphor. This metaphor - imagining a "paper purchase order" - helps him wrap his head around the structure of the objects and how they interact.

tagged: object creation construct child aggregate tutorial

Link: https://matthiasnoback.nl/2018/07/objects-should-be-constructed-in-one-go/

Trending Topics: