Skip to main content

What is a Value Object?

A Value Object is an immutable wrapper around a primitive value (string, number, boolean, or Date) that encapsulates domain behavior and validation. Two Value Objects with the same value are considered equal.

Key Characteristics

Primitive Values Only

Value Objects wrap a single primitive value: string, number, boolean, or Date.

Immutable

Once created, a Value Object cannot be changed. Use clone() to create new instances.

Equality by Value

Two Value Objects are equal if their primitive values are equal.

Self-Contained

Value Objects contain all the behavior related to the concept they represent.

Creating Value Objects

Value Objects accept only primitive types:

Basic Usage

Immutability

Value Objects are frozen on creation. To “change” a Value Object, use the clone() method:

Equality

Value Objects are compared by their primitive values:

Validation

Add schema validation to ensure Value Objects are always valid:

Lifecycle Hooks

Value Objects support lifecycle hooks for custom validation and side effects:

Available Hooks

  • onBeforeCreate: Called before validation, receives the primitive value
  • rules: Custom business rules, receives the ValueObject instance

Common Examples

Email

Price

Percentage

Slug

Serialization

ValueObjects automatically serialize to their primitive values: