Search⌘ K

Value Objects

Explore the concept of value objects in PHP functional programming. Understand how they represent entities by their values, enable equational reasoning for referential transparency, and facilitate domain validation. This lesson helps you grasp when and how to implement value objects effectively in your functional programming projects.

Overview

A value object is an abstract data type wherein each object represents an entity: the value. The grounds for a comparison of value objects is their value, not the identity of the object. The code below demonstrates this.

Code example

PHP
<?php
class HttpMessage
{
private int $code;
private string $response;
public function __construct(int $code, string $response)
{
$this->code = $code;
$this->response = $response;
}
public function verify(HttpMessage $message) : bool
{
return $this->response == $message->response &&
$this->code == $message->code;
}
public function newMessage(int $code, string $response) : HttpMessage
{
$newMessage = clone $this;
$newMessage->code = $code;
$newMessage->response = $response;
return $newMessage;
}
}
$ok = new HttpMessage(200, 'OK');
$created = $ok->newMessage(201, 'OK');
echo $ok->verify($created) ?
'Value objects are equal' :
'Value objects are not equal';

The class above is instantiable as an HTTP message value object. It ...