Lesson 4 of 45 · Small Objects, Big Impact
Value Objects
The validation creep
Have you ever worked on a project where part of the service class or a command handler class had validation checks before the main work started?
By validation checks I mean things like numbers less than 0 (calculating a price or discount percentage), checking if a string is in a valid format (an invoice number or invitation code), or a number being in a specific range (the maximum number of people in a team, latitude and longitude).
The usual first answer is that the validation for such business rules should be done as part of the request validation, or that it's fine to leave them in the service class.
The problem is that such business rules don't always come from an HTTP web request. There are other delivery mechanisms:
Webhooks
Console commands or cron jobs
A message queue such as Kafka or RabbitMQ
A third-party API response
These rules may need to be reused in multiple places, depending on the scenario. If the validation lives only in the form request, the webhook handler doesn't get it. The queue worker doesn't get it. The console command doesn't get it. Each delivery mechanism rediscovers the same rules and writes them again, slightly differently each time, until the rules drift apart and a bug ships.
Value objects don't replace request validation. Form requests still validate input at the boundary; value objects validate domain invariants once the input crosses into your business code.
The other problem is that the service class becomes more complex to manage and work with the more rules you add. The thing that was supposed to do "calculate price" is now doing "validate the inputs, validate the intermediate values, validate the result, and also calculate price". Most of the file is defending itself against the primitive types it was given.
Why primitives invite this
Primitive values like:
stringboolintfloat
only show the type of the value being processed. They don't show the correct format, and they don't tell you whether the value is valid by default.
You have to validate them every time.
This is the same problem the Primitive Obsession lesson named. The Data Transfer Objects lesson covered one cure (grouping fields). This lesson covers the deeper one (value objects, for giving each individual concept its own type with its own rules).
A Laravel example
Let's look at some Laravel code that shows the pattern (Room is an Eloquent model with the columns used here):
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Booking\Room;
use Carbon\Carbon;
use InvalidArgumentException;
final class CalculateReservationPriceService
{
public function calculate(int $roomId, string $checkIn, string $checkOut): int
{
$room = Room::find($roomId);
$start = Carbon::parse($checkIn);
$end = Carbon::parse($checkOut);
$nights = (int) $start->diffInDays($end);
if ($nights <= 0) {
throw new InvalidArgumentException('Stay must be at least one night');
}
$priceInCents = $room->nightly_rate_cents * $nights;
if ($priceInCents < 0) {
throw new InvalidArgumentException('Price cannot be negative');
}
if ($nights >= 7 && $room->has_weekly_discount) {
$discount = $room->weekly_discount_percent;
if ($discount < 0 || $discount > 100) {
throw new InvalidArgumentException('Invalid discount percentage');
}
$priceInCents = (int) round($priceInCents * (1 - $discount / 100));
}
return $priceInCents;
}
}In short, the service is trying to:
Calculate the number of nights
Calculate the normal price
Calculate a special price with a discount applied if the stay is for 7 nights or more and the room has a weekly discount
If we focus on the normal price calculation:
Is the price calculated in cents or in floats?
Is the price in dollars or in euros?
Is the price below zero?
Can the price even be below zero?
The same questions can be asked of the discounted price. The service is the only thing answering them, with if statements that have to be remembered every single time anyone calculates a price anywhere else in the system.
So what's the solution?
Value objects
Value objects are objects that:
Represent a value.
Are immutable, meaning they cannot be changed once instantiated.
Can represent one or multiple values.
Validate the value before the object is instantiated.
Can offer named constructors for the different ways to build them.
Have methods that convert, compare, or format the value.
Do not have an identity.
That last point is the line between a value object and an entity. Two Price objects with the same amount are interchangeable; nothing distinguishes one from the other. Two Guest objects with the same data are still two different guests, because each one has its own identity. Value objects don't.
A simple value object
Let's see what a Price value object looks like:
<?php
declare(strict_types=1);
namespace App\Pricing;
use InvalidArgumentException;
final readonly class Price
{
public function __construct(public int $amountInCents)
{
if ($amountInCents < 0) {
throw new InvalidArgumentException('Price cannot be negative');
}
}
public static function fromCents(int $amountInCents): self
{
return new self($amountInCents);
}
public static function fromDollars(float $amountInDollars): self
{
return new self((int) round($amountInDollars * 100));
}
public function convertToDollars(): float
{
// Float here is for display only. Never store or do arithmetic
// on this value; use amountInCents for that. The Primitive Obsession lesson covers why.
return $this->amountInCents / 100;
}
public function formattedWithSymbol(): string
{
return '$' . number_format($this->convertToDollars(), 2);
}
public function multiplyBy(int $multiplier): self
{
return new self($this->amountInCents * $multiplier);
}
public function applyDiscountPercent(int $percent): self
{
if ($percent < 0 || $percent > 100) {
throw new InvalidArgumentException('Discount must be between 0 and 100');
}
return new self((int) round($this->amountInCents * (1 - $percent / 100)));
}
public function equals(Price $other): bool
{
return $this->amountInCents === $other->amountInCents;
}
}As you can see in the example:
The class has named constructors (static methods like
fromCentsandfromDollars).It has a dollar conversion method,
convertToDollars.It has validation logic in the constructor, which refuses to create a negative price.
It has a formatted version with the dollar sign in front,
formattedWithSymbol().Behavior that returns a new price (
multiplyBy,applyDiscountPercent) returns a new instance instead of mutating this one. That's the immutable part.
Here's how it gets used in the calling code:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Booking\Room;
use App\Pricing\Price;
use Carbon\Carbon;
use InvalidArgumentException;
final class CalculateReservationPriceService
{
public function calculate(int $roomId, string $checkIn, string $checkOut): Price
{
$room = Room::find($roomId);
$nights = (int) Carbon::parse($checkIn)->diffInDays(Carbon::parse($checkOut));
if ($nights <= 0) {
throw new InvalidArgumentException('Stay must be at least one night');
}
$nightlyRate = Price::fromCents($room->nightly_rate_cents);
$normalPrice = $nightlyRate->multiplyBy($nights);
$finalPrice = $nights >= 7 && $room->has_weekly_discount
? $normalPrice->applyDiscountPercent($room->weekly_discount_percent)
: $normalPrice;
return $finalPrice;
}
}The stay-length rule stays in the service because it belongs to the dates, not to a price. The return type changed from int to Price, so callers get a typed value instead of a bare number.
Look at what disappeared from the service:
The "is this number negative?" check.
The "is the discount between 0 and 100?" check.
The "in cents or in dollars?" question.
The mental tax of remembering the conventions every time.
All of it lives in Price now. The service describes the business rule and nothing else.
Two kinds of value objects
There are two kinds:
Simple. They represent a single value.
Complex. They represent multiple values that travel together.
The Price example above is a simple value object, because it represents a single primitive value (cents).
Price is a teaching example for this lesson. The rest of the course uses Money, which carries a currency. If this were a complex value object, it would represent the currency as well, because in real systems "200 in some currency" isn't a price, "200 USD" is. The complex version looks like this (the constructor is public for now; the next lesson makes it private):
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exceptions\MismatchedCurrencies;
use InvalidArgumentException;
final readonly class Money
{
public function __construct(
public int $amountInCents,
public Currency $currency,
) {
if ($amountInCents < 0) {
throw new InvalidArgumentException('Money cannot be negative');
}
}
public static function fromCents(int $amountInCents, Currency $currency): self
{
return new self($amountInCents, $currency);
}
public function add(Money $other): self
{
if (!$this->currency->equals($other->currency)) {
throw new MismatchedCurrencies($this->currency, $other->currency);
}
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
public function format(): string
{
return $this->currency->format($this->amountInCents);
}
public function equals(Money $other): bool
{
return $this->amountInCents === $other->amountInCents
&& $this->currency->equals($other->currency);
}
}<?php
declare(strict_types=1);
namespace App\Billing;
use InvalidArgumentException;
final readonly class Currency
{
private const SUPPORTED = ['USD', 'EUR', 'GBP'];
private const SYMBOLS = ['USD' => '$', 'EUR' => '€', 'GBP' => '£'];
public function __construct(public string $isoCode)
{
if (!in_array($isoCode, self::SUPPORTED, true)) {
throw new InvalidArgumentException("Unknown currency: {$isoCode}");
}
}
public function equals(Currency $other): bool
{
return $this->isoCode === $other->isoCode;
}
public function format(int $amountInCents): string
{
// Float here is for display only.
return self::SYMBOLS[$this->isoCode] . number_format($amountInCents / 100, 2);
}
}Money::add throws MismatchedCurrencies when the currencies differ:
<?php
declare(strict_types=1);
namespace App\Billing\Exceptions;
use App\Billing\Currency;
use InvalidArgumentException;
final class MismatchedCurrencies extends InvalidArgumentException
{
public function __construct(Currency $left, Currency $right)
{
parent::__construct("Cannot combine {$left->isoCode} with {$right->isoCode}");
}
}Now adding USD to EUR throws an exception. The system can't lose track of what currency a price is in, because the price always knows. The "did somebody store dollars in a euros field?" class of bug becomes much harder to introduce.
Money is a complex value object made up of an int and a Currency value object. A complex value object is a small graph of simpler values, with their own combined invariants on top.
For money specifically, the moneyphp/money library is a widely used implementation. On a serious financial product, reaching for it is reasonable.
Where value objects show up
You can use value objects whenever you work with:
Money
Addresses
Email addresses
Phone numbers
Latitude and longitude
Invitation codes
Invoice numbers
Discount percentages
Date ranges and periods
Slugs and URLs
Time-of-day and timezone-bound timestamps
and many more
Anything that has a format, a constraint, a calculation, or a comparison rule attached to it is a candidate for a value object. The bigger the rules around the concept, the more obviously a value object earns its place. A loop counter is int $i, and wrapping every variable is the over-engineering trap.
Value objects vs data transfer objects
Price and the RequestReservationData data transfer object look alike from a distance. Both are final readonly classes with typed properties and static constructors, but they do different jobs.
Data transfer objects carry data from one place to another. They trust their input, because validation already happened at the boundary (the form request).
Value objects represent one concept, and they refuse any value that breaks that concept's rules.
Here's a data transfer object that carries a new nightly rate from an admin form to a service:
<?php
declare(strict_types=1);
namespace App\Pricing;
final readonly class ChangeNightlyRateData
{
public function __construct(
public int $roomId,
public int $nightlyRateCents,
) {}
public static function fromArray(array $data): self
{
return new self(
roomId: (int) $data['room_id'],
nightlyRateCents: (int) $data['nightly_rate_cents'],
);
}
}new ChangeNightlyRateData(12, -500) builds without complaint, because the data transfer object has no opinion on whether -500 is a valid rate. Price::fromCents(-500) throws, because a negative price breaks the rule Price exists to enforce.
The service is where the two meet:
<?php
declare(strict_types=1);
namespace App\Pricing;
use App\Booking\Room;
final class ChangeNightlyRateService
{
public function change(ChangeNightlyRateData $data): void
{
$rate = Price::fromCents($data->nightlyRateCents);
$room = Room::findOrFail($data->roomId);
$room->nightly_rate_cents = $rate->amountInCents;
$room->save();
}
}The data transfer object gets the number to the service, and Price decides whether the number is allowed. If a second entry point shows up later, such as a CSV import or a console command, and it skips validation, Price still refuses -500.
A data transfer object can also hold value objects. The next lesson changes RequestReservationData so its fields are GuestId, RoomId, DateRange and GuestCount instead of strings and ints. It's still a data transfer object: each field checks its own rules, and the class adds none of its own. The Data Transfer Objects lesson described the point where that changes: "A DTO that validates its own data is turning into a value object."
When you can't tell which one you're looking at, ask what the class refuses. A data transfer object refuses nothing beyond what its property types refuse. A value object refuses every value that breaks a rule of the concept it represents.
Value objects vs entities
The only thing that differentiates a value object from an entity is identity.
Value objects are equal if their values are equal. Two
Price::fromCents(2000)instances are interchangeable. They're "the same price".Entities have an identifier. Two
Guestrecords with id 17 and id 42 are two different guests, even if every other field is identical. They have a distinct existence in the world.
If you're modeling something that has a database row of its own, it's probably an entity. If you're modeling a value that happens to be carried by an entity (the guest's email, the reservation's total, the stay's date range), it's probably a value object.
This distinction comes up in the Anemic Models vs Rich Models lesson. For now, the practical rule is: if it has an id, it's an entity. If not, value object.
What value objects buy you
Here's the list of what gets cheaper:
Validation lives in one place. The constructor refuses invalid values. Every consumer gets a guaranteed-valid object, no
ifstatements required.Behavior lives with the data. Formatting, comparing, converting, combining. All on the type that owns the concept.
Immutability rules out an entire class of bugs. A
Pricecan't be silently mutated three function calls deep. If you need a different price, you build a new one.The type system catches mistakes. Pass a
Pricewhere aDistancewas expected, and the IDE underlines it.Service classes get smaller. All the validation boilerplate moves out, and the service is left with the actual business rule it was supposed to express.
A practical sequence
If you want to introduce value objects to a real codebase, the cheapest way to start is small.
Find a service class with three or more validation checks before its real work begins. Those checks are screaming for a value object.
Pick one of them. Lift it into a class. Move the validation into the constructor. Move any helper methods into instance methods.
Replace the primitive in the service signature with the value object. Watch the validation disappear from the service body.
See whether the team finds it useful. If yes, the next service that hurts gets the same treatment.
The one thing to remember
A primitive tells you what shape a value has. A value object tells you what the value is, what it's for, what it can and can't do. The cost is one small class. The benefit is that all the validation and behavior around the concept lives in one place, and the rest of the codebase stops having to remember.
Related Links
- moneyphp/moneyA widely used Money value object implementation in PHP, covering currency handling this lesson's trimmed example leaves out.
- Value ObjectFowler's description of why objects that are equal by value rather than by reference need their own category.
- Is it a DTO or a Value Object?Matthias Noback on the line between a plain data holder and a value object that guards its own invariants.
- Readonly propertiesThe PHP manual page for the readonly modifier this lesson's value objects rely on.