A better way of writing value objects in PHP

Quick introduction to value objects

$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

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
Chris Harrison

Chris Harrison

Software engineer

More from Medium

Converting Your Test Suite to PEST

Get started with Symfony 6 for beginners

RabbitMQ and Drupal, a perfect match

Including external OpenAPI models in your own OpenAPI definition