A better way of writing value objects in PHP

Quick introduction to value objects

A value object is a concept from Domain Driven Design. They are objects whose equality is not dependent on identity.

$location1 = new Location(1.2902, 103.8519);
$location2 = new Location(1.2902, 103.8519);
$id1 = 1021;
$id2 = 1031;
$userId = 9302;
$products = [2901, 9303, 0185];
$order1 = new Order($id1, $userId, $productIds);
$order2 = new Order($id2, $userId, $productIds);

Our approach

You should not be relying on a library to define your value objects. Value objects are just values in your domain. They should be completely specific to your business logic. In an ideal world, they should just be pure PHP objects, written from scratch for each value in your domain.

public function changeUserEmail(GenericIdObject $id, GenericEmailObject $email);
public function changeUserEmail(UserId $id, Email $email);
class UserId extends GenericIdObject {
...
  • a small interface (it’s as tiny as we think it can be whilst still being useful)
  • a set of PHP traits you can use to help implement the interface
interface ValueObject
{
public function isNull(): bool;
public function isSame(ValueObject $object): bool;
public static function fromNative($native);
public function toNative();
}
  • isNull A simple boolean value of whether the value is null or not.
  • isSame Whether the value of this ValueObject can be considered equivalent to another ValueObject
  • fromNative and toNative are essentially for serialisation. For getting your value objects in and out of your application (e.g. persisting and retrieving from a database)

--

--

Software engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store