Entities & Value Objects
"When you care only about the attributes and logic of an element of the model, classify it as a value object. Make it express the meaning of the attributes it conveys and give it related functionality. Treat the value object as immutable." — Eric Evans, Domain-Driven Design Reference (2015), "Value Objects"
Summary: An entity is something whose identity runs through time while its attributes change; a value object is something described completely by its attributes, immutable, equal by value and replaced rather than edited. Most of a good domain model is value objects; entities are the few things you must follow over time. Focus: The identity question ("do we care which one?"), choosing and generating identities (natural vs surrogate, UUIDv7, typed OrderId), always-valid value objects with invariants in constructors, immutability in Go and PHP 8.4, side-effect-free functions and closure of operations (Money + Money = Money), conceptual contours and whole values versus primitive obsession, equality and hashing pitfalls (floats, time zones, Persian digits), enums as values, persistence mapping (embedded columns, JSON, dependent tables, Scanner/Valuer, Eloquent casts), values at the API edge and in events, and testing values with property-based and fuzz tests. Learning goal: Given a domain concept, decide entity or value with a reason; implement the Order entity and its value objects (OrderId, Money, Quantity, ShippingAddress, PhoneNumber, OrderLine) in Go and Laravel so that an invalid instance cannot exist; persist and serialise them without leaking the model; and spot the anti-patterns in a code review.
This chapter opens group DD 02 (Tactical Design). It assumes the strategic chapters: the Sales, Fulfilment, Billing, Catalog and Identity contexts of our online shop (Bounded Context) and their words (Ubiquitous Language). The object-oriented basics of identity versus equality are on Object-Oriented Modeling; this page is the DDD treatment and goes much further. It owns what kind of object is this, and how do I build it so it cannot be wrong? The neighbours own the rest: which objects change together in one transaction (Aggregates & Factories), why behaviour belongs on these objects (Anemic vs Rich Domain Models), loading and saving them (Repositories, Data Persistence in Design), where logic that fits neither lives (Domain, Application & Infrastructure Services), and what to publish when they change (Domain Events vs Integration Events). The internals of UUIDs, ULIDs and Snowflake ids are on ID Generation at Scale.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why the distinction pays for itself | Why it exists |
| Evans 2003, Fowler, Vernon, Ward Cunningham's Whole Value | Where it comes from |
| Identity through time, equality by id | Entity |
| Immutable, equal by value, replaceable | Value object |
| "Do we care which one?" | The identity question |
Natural vs surrogate, UUIDv7, who generates, OrderId | Choosing and generating identity |
| Always-valid objects, fail fast vs collect errors | Invariants and self-validation |
final readonly class, unexported fields, with-ers, aliasing | Immutability |
| Money + Money = Money, allocation | Side-effect-free functions and closure of operations |
| Primitive obsession, Whole Value, conceptual contours | Whole values and conceptual contours |
| Floats, time zones, Persian digits, map keys | Equality and hashing pitfalls |
| Backed enums, Go typed constants | Enums as value objects |
Is OrderLine a value or an entity? | Entities composed of values; the OrderLine debate |
| Embedded columns, JSON, dependent tables, casts, Scanner/Valuer | Mechanics: persistence mapping |
| DTOs, events, messages | Mechanics: values at the edge |
| Error messages you will meet | Mechanics: errors |
| Full code with tests | Go, Laravel |
| Mutable VOs, public setters, VOs with ids, Eloquent as entity | Solving the classic problems |
| Which tool for which concept | Choosing |
| Monolith to distributed data | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The two building blocks. Every row is unpacked in the concept catalogue.
| Entity | Value object | |
|---|---|---|
| In plain words | A thing we follow over time | A description, a measure, an amount |
| Defined by | Identity (an id) | All of its attributes |
| Equality | Same id = same thing, even if every attribute differs | Same attributes = equal, even if different instances |
| Changes | Through methods that guard rules; it has a lifecycle | Never; you replace it with a new one |
| Example in Sales | Order, Customer (in Identity), Shipment (in Fulfilment) | Money, Quantity, ShippingAddress, Email, OrderId, OrderStatus |
| Go shape | Pointer *Order, unexported fields, SameAs | Struct with unexported comparable fields, ==, methods return new values |
| PHP 8.4 shape | final class with public private(set) properties | final readonly class with equals() |
| Persisted as | Its own row with a primary key | Columns on the owner, a JSON column, or rows of a dependent table |
The value-object checklist (Evans's and Vernon's characteristics):
| Property | Plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Measures, quantifies or describes | It says how much or what kind | 22.50 EUR, 3 units, Tehran 12345-67890 | Behaviour has no home, so it spreads into services |
| Immutable | Cannot be changed after construction | price.Add(tax) returns a new Money | Aliasing bug: one change shows up in two orders |
| Conceptual whole | Attributes that mean something together | amount + currency, start + end | Someone adds EUR cents to USD cents |
| Replaceable | Change = assign a new one | order.ShipTo(newAddress) | order.address.city = ... skips validation |
| Value equality | Equal when all attributes are equal | two 22.50 EUR are equal | Duplicates in sets, broken map keys |
| Side-effect-free | Operations only compute and return | Allocate(1,1,1) | Calculations that also write are untestable |
| Self-validating | Cannot exist in an invalid state | NewQuantity(0) fails | Every caller re-checks, some forget |
Where values live (details in Mechanics):
| Concept | Kind | Storage | API / event shape |
|---|---|---|---|
OrderId | Value used as identity | uuid column, primary key | "id": "0190..." string |
Money | Value | Two columns: total_minor bigint, total_currency char(3) | {"amount_minor": 2250, "currency": "EUR"} |
ShippingAddress | Value | One jsonb column | Explicit DTO fields |
OrderLine x N | Value inside the entity | Dependent table order_lines, key (order_id, sku) | Array of DTOs |
OrderStatus | Enum value | text with CHECK | "status": "placed" |
Order | Entity | Row in orders + its lines | OrderDTO, OrderPlacedV1 |
Why it exists
Software that models a business is mostly about two kinds of things: things the business follows (this order, that customer, this parcel) and things that describe them (an amount, an address, a date range). Evans's point is that the two need different handling, and that attaching identity to everything is a cost: "Tracking the identity of entities is essential, but attaching identity to other objects can hurt system performance, add analytical work, and muddle the model by making all objects look the same."
| Treating everything as an entity | Separating entities from values |
|---|---|
| Every object gets an id, a table, a repository | Only things with a lifecycle get ids |
| Equality is "same row" everywhere | Equality matches the business meaning |
| Attributes are primitives with setters | Attributes are small types with rules |
| Validation is scattered in controllers and services | Validation lives in the value's constructor |
| Shared mutable objects cause aliasing bugs | Values are immutable and safe to share |
| Tests need a database | Values are tested as pure functions |
The everyday picture, reused through the page. Think of a banknote and a passport. If a friend owes you 10 euros, you do not care which 10-euro note comes back: any note of the same value settles the debt. That is a value. A passport is different: two passports may show the same name and birth date, but border control cares which passport it is, follows it through renewals and photo changes, and it has a lifecycle (issued, valid, expired, revoked). That is an entity. (A central bank does track serial numbers: in its context a note is an entity. Same thing, different context.)
Three common misunderstandings, up front
- "Entity means a database table, value object means a column." No. Fowler warns that "Entity is often used to represent a database table or an object that corresponds to a database table"; in DDD it means an object with identity. A value object may be stored in its own table (order lines) and an entity may be stored in a JSON document.
- "Value objects are just DTOs." No. Around 2000 some J2EE books called data-transfer objects "value objects"; Fowler notes the usage "has mostly disappeared by now". A DDD value object has behaviour and invariants; a DTO has neither.
- "Whether it is an entity is a property of the thing." No. It is a decision of the model in one bounded context. An address is a value in Sales and could be an entity in a postal-registry context.
Where it comes from
- Ward Cunningham, Whole Value. The idea of objects that represent a whole quantity of the domain instead of bare numbers and strings. Vernon credits him when distinguishing a "Value-typed property" from "a simple attribute such as a string or numeric type ... as does Ward Cunningham when describing Whole Value" (Vernon, Implementing DDD, ch. 10 note, free sample). We did not read Cunningham's original text and cite him only through Vernon.
- Martin Fowler, Patterns of Enterprise Application Architecture (catalogue pages dated 5 March 2003). Catalogued Value Object, Money ("it's always puzzled me that money isn't actually a first class data type in any mainstream programming language"), and the persistence patterns used on this page: Embedded Value, Serialized LOB and Dependent Mapping.
- Eric Evans, Domain-Driven Design (2003). Made Entity, Value Object and Service the core building blocks and added the supple-design patterns this page leans on: Side-Effect-Free Functions, Assertions, Conceptual Contours and Closure of Operations. The free DDD Reference (2015) restates them. Fowler's Evans Classification (14 December 2005) summarises the trio.
- Vaughn Vernon, Implementing Domain-Driven Design (2013). Chapter 5 (Entities) and chapter 6 (Value Objects). The table of contents in the publisher's free sample names the ground covered: identity "User Provides Identity", "Application Generates Identity", "Persistence Mechanism Generates Identity", "Another Bounded Context Assigns Identity", "Surrogate Identity", "Identity Stability"; and for values "Measures, Quantifies, or Describes", "Immutable", "Conceptual Whole", "Replaceability", "Value Equality", "Side-Effect-Free Behavior", "Standard Types Expressed as Values", and five persistence options from "ORM and Single Value Objects" to "ORM and Enum-as-State Objects". His summary of the case study: the team "focused too intensely on the individual attributes of Entities when they should have been giving careful consideration to how multiple related attributes are properly gathered as an immutable whole."
- Fowler, Value Object (14 November 2016). The modern short statement: "Objects that are equal due to the value of their properties ... are called value objects", plus the aliasing-bug argument for immutability.
- Languages caught up. PHP 8.1 added
readonlyproperties and enums, 8.2readonlyclasses, 8.4 property hooks and asymmetric visibility, 8.5 (released 20 November 2025)clone()with property overrides, which the release notes say makes the with-er pattern "simple for readonly classes". Go has had comparable structs since 1.0 and generics since 1.18. Laravel's Eloquent gained custom casts andCastablevalue objects; Laravel 13'sHasUuids"will generate UUIDv7 identifiers" by default.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, a comparison table, and the fix in code.
Entity Must-know
In plain words: an entity is something we keep track of as the same one while its details change, like an order that goes from draft to dispatched.
Common misunderstanding: "An entity is anything with an id column." Many objects get an id only because the ORM wants one. The test is not "does it have an id?" but "would the business be wrong if we mixed up two instances that look identical?"
Definition: Evans: "Many objects represent a thread of continuity and identity, going through a lifecycle, though their attributes may change." The prescription: "When an object is distinguished by its identity, rather than its attributes, make this primary to its definition in the model. Keep the class definition simple and focused on life cycle continuity and identity." And the line that settles arguments: "The model must define what it means to be the same thing." Fowler adds that entities are a common form of reference object, and that values override equality "while entities usually don't".
Order 0190f3c2-... in the Sales context
1 09:00 NewOrder(id, customer cus-7, EUR) status=draft lines=0
2 09:02 AddLine(SKU-42, 2, 12.50 EUR) lines=1 total=25.00 EUR
3 09:03 ShipTo(Tehran, 12345-67890) address replaced (value)
4 09:05 Place(now) status=placed
5 14:00 MarkPaid (Billing event) status=paid
6 +2d MarkDispatched (on ParcelDispatched) status=dispatched
Every attribute changed; SameAs(order at step 1) is still true: same id.Real scenario: two customers named "Sara Ahmadi" in Tehran with the same e-mail domain must not be merged (Identity context). A support agent says "the order from yesterday": the system must find it by number although its status, total and address changed. A refund must go to this payment, not to another payment of the same amount on the same day.
How each technology expresses identity:
| Technology | Identity mechanism | Equality you get by default | What you add |
|---|---|---|---|
| Go | Pointer *Order in memory; OrderID field | == on pointers = same variable; on structs = all fields | SameAs(other) comparing ids |
| PHP 8.4 | Object handle | === same instance; == same class and equal properties | sameAs() comparing OrderId |
| Eloquent | Primary key + table + connection | $a->is($b) compares "the same primary key, table, and database connection" | Map to a domain Order if logic is rich |
| PostgreSQL | PRIMARY KEY | Row identity | Immutable key, never reused |
Fix / how to use it: keep entities small and behavioural: identity, lifecycle state, intention-revealing methods (Go: AddLine, ShipTo, Place), and value objects for everything descriptive. Give the id from outside the constructor so retries can reuse it (identity). No public setters (anti-pattern).
Value object Must-know
In plain words: a value object is a small, unchangeable description, like "22.50 EUR" or "3 units"; two of them with the same content are simply equal.
Common misunderstanding: "A value object is a struct without an id." That is only the absence of identity. Evans: "if we think of this category of object as just the absence of identity, we haven't added much to our toolbox or vocabulary." A value object carries meaning and behaviour: Money knows its currency, adds only to the same currency, and allocates without losing a cent.
Definition: Evans: "When you care only about the attributes and logic of an element of the model, classify it as a value object. Make it express the meaning of the attributes it conveys and give it related functionality. Treat the value object as immutable. Make all operations Side-effect-free Functions that don't depend on any mutable state. Don't give a value object any identity and avoid the design complexities necessary to maintain entities." Fowler's Evans Classification: "Objects that matter only as the combination of their attributes. Two value objects with the same values for all their attributes are considered equal."
Two lines priced from the catalogue
1 a := Money{2250, EUR} // from SKU-42 price
2 b := Money{2250, EUR} // parsed from "22.50" in a cart request
3 a == b -> true (value equality; different variables)
4 c, _ := a.Add(b) -> Money{4500, EUR}; a and b unchanged
5 seen := map[Money]int{a: 1}; seen[b] -> 1 (equal values are equal keys)Real scenario: prices, totals, discounts, tax amounts (Money, Percentage); stock and order quantities (Quantity); campaign windows and delivery slots (DateRange); shipping and billing addresses; contact data (Email, PhoneNumber); identifiers themselves (OrderId is a value that serves as an entity's identity).
Language support for values:
| Language | Value-object building blocks | Gotcha |
|---|---|---|
| Go | Struct with unexported fields, constructor NewX, value receivers, == when all fields comparable | Slices/maps inside make the struct non-comparable; time.Time == compares Location and monotonic reading |
| PHP 8.4 | final readonly class, private constructor + named constructors, enums | readonly does not stop "interior mutability" of objects stored inside; hooks are "incompatible with readonly properties" |
| PHP 8.5 | clone($this, ['field' => $v]) for with-ers | Laravel 13 requires PHP 8.3, so do not rely on 8.5 in shared code |
| Eloquent | CastsAttributes, Castable::castUsing, enum casts, Attribute::make | The docs' example mutates the cast object in place; with readonly values you assign a new one |
| PostgreSQL | CREATE DOMAIN, composite types, CHECK | A domain constrains storage; it does not give your code behaviour |
Fix / how to use it: make the value the first thing you reach for. In Go: type Money struct{ minor int64; currency Currency } plus NewMoney, methods returning Money. In PHP: final readonly class Money with a private constructor and ofMinor() / parse(). Code in Go and Laravel.
The identity question Must-know
In plain words: ask "if I swapped this one for another that looks exactly the same, would anyone in the business care?" If yes, entity; if no, value.
Common misunderstanding: "If it changes, it is an entity." Values describe things that change all the time (a customer's address, an order's total); the holder changes by replacing the value. Change is not the test; continuity of identity is.
Definition: the decision is made per bounded context by asking what the domain expert means by "the same". Vernon's rule of thumb for parts of an aggregate: "Cases where instances can be completely replaced point to the use of a Value Object rather than an Entity." And: "Choose to model a contained Aggregate part as a Value Object rather than an Entity whenever possible."
Modelling conversation, Sales context
1 Dev: "When the customer edits the address on a draft order, is it the same address?"
2 Expert: "Who cares? We ship to whatever is on the order when it is placed."
3 Dev: -> ShippingAddress is a value; ShipTo() replaces it.
4 Dev: "Two orders with identical lines from the same customer: one order or two?"
5 Expert: "Two. Each has its own number, payment and shipment."
6 Dev: -> Order is an entity with OrderId.
7 Dev: "Two lines for SKU-42 in one order?"
8 Expert: "No, we merge them: one line per product."
9 Dev: -> OrderLine is identified by SKU inside its Order; no line id needed (see the debate).Real scenario (same word, different answers):
| Concept | Context where it is a value | Context where it is an entity | Why it differs |
|---|---|---|---|
| Address | Sales: where to ship this order | Postal registry, delivery-route planning | The registry follows one address through renames and geocode fixes |
| Seat | Cinema with free seating per row class | Airline: seat 14C on flight IR712 | Airlines sell a specific seat |
| Money | Everywhere in Sales and Billing | Central bank tracking serial numbers | Serial numbers matter only for the bank |
| Product price | Sales line: price at the time of ordering | Catalog: PriceListEntry with validity and audit | Catalog manages it over time |
| Customer | Billing invoice: "bill-to" snapshot | Identity: the account | Billing wants what was true at invoicing |
Fix / how to use it: write the answer into the glossary of the context (Ubiquitous Language) and into the type: a value type with no id, or an entity with a typed id.
Choosing and generating identity Must-know
In plain words: an entity needs an identifier that never changes, is unique, and is available when you need it; who creates it and in what format are design decisions.
Common misunderstanding: "The database auto-increment is the identity." It is one option with a big drawback: the id does not exist until the INSERT, so you cannot put it into events, idempotency keys or a second write in the same use case without a round trip, and it leaks business volume when exposed.
Definition: Evans: "Define an operation that is guaranteed to produce a unique result for each object, possibly by attaching a symbol that is guaranteed unique. This means of identification may come from the outside, or it may be an arbitrary identifier created by and for the system, but it must correspond to the identity distinctions in the model." Vernon's chapter headings list four sources (user, application, persistence mechanism, another bounded context) plus "Surrogate Identity" and "Identity Stability"; in our reading, a surrogate is a database key kept alongside the domain id, and stability means the id never changes. RFC 9562 defines UUIDv7: "UUIDv7 features a time-ordered value field derived from the widely implemented and well-known Unix Epoch timestamp source".
| Source / format | Example | When it is available | Pros | Cons |
|---|---|---|---|---|
| Natural key from the domain | ISBN, national code, IBAN | Before creation | Meaningful, dedups naturally | Can change, be mistyped, or be personal data |
| User provides | Username, coupon code | Before creation | Human-friendly | Uniqueness checks, renames |
Database sequence / AUTO_INCREMENT | orders.id = 1042 | After INSERT | Small, ordered | Late; guessable; hard across shards |
| Application UUIDv4 | random 122 bits | Before persistence | Generated anywhere | Random index inserts (locality) |
| Application UUIDv7 / ULID | 0190f3c2-... | Before persistence | Time-ordered, index-friendly | Leaks creation time |
| Another context assigns | Payment id from the PSP | After the other system answers | Correlates with the source | Dependency on that system |
Checkout with an application-generated OrderId (UUIDv7)
1 Browser POST /checkout Idempotency-Key: k-77
2 App: id := NewOrderID(now) -> 0190f3c2-7b1e-7... (no DB round trip)
3 App: BEGIN; INSERT orders(id=...); INSERT outbox(OrderPlacedV1{order_id=...}); COMMIT
4 Network drops the response; browser retries with k-77
5 App: idempotency table maps k-77 -> 0190f3c2-...; returns the same order
With auto-increment, step 3 would need INSERT ... RETURNING id before building the event.Real scenario: an order number shown to customers ("IR-2026-004211") is a separate display value, not the primary key, so it can be formatted, shortened and changed. A shipment id assigned by the carrier is an identity from "another bounded context" and is stored as a value on our Shipment. A CustomerId in Sales is a reference value to the Identity context, never an object pointer (Aggregates).
Typed ids. Wrap the id in its own value type (OrderId, CustomerId) so the compiler refuses cancel(customerId) where an OrderId is expected, and so parsing and formatting live in one place.
Fix / how to use it: Go: NewOrderID(now) builds a UUIDv7 from crypto/rand per RFC 9562 (snippet below). Laravel: OrderId::generate() wraps Str::uuid7(); on an Eloquent model, the HasUuids trait generates UUIDv7 by default. Deeper comparison of formats and their index behaviour: ID Generation at Scale.
Invariants and self-validation Must-know
In plain words: a value object checks its own rules when it is created, so every instance that exists is valid; nobody has to check again.
Common misunderstanding: "Validation belongs in the controller or form request." Request validation checks input shape for one endpoint. Invariants are domain rules that must hold for every path: HTTP, queue consumer, CLI import, test fixture. Put the rule where no path can skip it.
Definition: Evans's Assertions: "State post-conditions of operations and invariants of classes and aggregates. If assertions cannot be coded directly in your programming language, write automated unit tests for them." An always-valid (self-validating) object enforces its invariants in its constructor (or named constructors) and in every operation that produces a new instance; there is no way to obtain an invalid instance except through deliberate rehydration code.
Fail fast or collect errors? For one value (a quantity), throw or return the first error. For a value assembled from a form (an address), Fowler's advice in Replacing Throwing Exceptions with Notification in Validations applies: "If you're validating some data, you usually shouldn't be using exceptions to signal validation failures." Collect all problems and report them together; our ShippingAddress returns one error listing every problem.
Three entry points, one rule: quantity must be 1..50 per line
1 HTTP POST /cart/lines {"qty": 0} -> NewQuantity(0) -> ErrInvalidQuantity -> 422
2 Queue ImportB2BOrder{qty: 120} -> NewQuantity(120) -> ErrInvalidQuantity -> DLQ
3 Code line.Quantity().Add(q30) with 30 -> NewQuantity(60) -> ErrInvalidQuantity
No path reaches Order.AddLine with an invalid Quantity, because none can construct one.Real scenario: a B2B import that bypassed the controller and created lines with quantity 0; an address with a 9-digit postal code that made the carrier API reject a whole batch; a percentage of 120% applied as a discount.
| Approach | Where the rule lives | Who can bypass it | Use for |
|---|---|---|---|
| Form request / handler validation only | Edge | Every non-HTTP path | Input shape, UX messages |
Database CHECK / DOMAIN only | Storage | Code that never saves, or other databases | Last line of defence |
| Self-validating value object | Constructor | Only explicit rehydration | Domain invariants |
| All three, with the VO as the source of truth | Layered | Nobody | Production systems |
Fix / how to use it: Go returns (T, error) from NewX with sentinel errors (errors.Is(err, ErrInvalidQuantity)); PHP throws a domain exception (InvalidValue) from the constructor. Keep messages in the ubiquitous language. Map them to HTTP 422 at the edge.
Immutability Must-know
In plain words: once made, a value never changes; to "change" it you make a new one and put that in its place.
Common misunderstanding: "Immutability is about performance or threads." It helps there, but the domain reason is aliasing: when two holders share one mutable value, a change through one shows up in the other. Fowler: "To avoid aliasing bugs I follow a simple but important rule: value objects should be immutable. If I want to change my party date, I create a new object instead."
Definition: a value object has no operation that changes its observable state; derived values are returned as new instances. In PHP 8.2+, "Marking a class as readonly will add the readonly modifier to every declared property, and prevent the creation of dynamic properties." In Go there is no readonly; immutability is achieved by unexported fields, a constructor, value receivers that return new values, and defensive copies of slices and maps.
Aliasing bug with a mutable Address shared by two orders
1 addr := &Address{City: "Tehran"}
2 o1.shipTo = addr; o2.shipTo = addr // "reuse last address" feature
3 o2.shipTo.City = "Shiraz" // customer edits order 2
4 o1 now ships to Shiraz // nobody touched order 1
With an immutable value: o2.ShipTo(NewShippingAddress(... "Shiraz" ...)); o1 unchanged.Techniques per language:
| Technique | Go | PHP 8.4 | PHP 8.5 |
|---|---|---|---|
| Prevent writes | Unexported fields; no setters | final readonly class | same |
| Construct valid | NewX(...) (X, error) | Private constructor + named constructors | same |
| "With-er" | Value receiver: func (l OrderLine) WithQuantity(q Quantity) OrderLine { l.quantity = q; return l } | return new self(...all fields...) | return clone($this, ['quantity' => $q]); |
| Collections inside | Return slices.Clone(x); never expose the backing array | Arrays are copied on write; objects inside are not | same |
| Stop subclass mutation | No inheritance | final | same |
PHP 8.5's clone with overrides, from the release notes:
// PHP 8.5 only. Laravel 13 supports PHP 8.3+, so keep new self(...) in shared code.
public function withAlpha(int $alpha): self
{
return clone($this, [
'alpha' => $alpha,
]);
}Real scenario: a "default address" object cached in memory and shared across requests in a long-running worker (Laravel Octane, a Go service) where one request's edit leaked into another; a Money instance passed into a discount function that modified it, so the cart total and the invoice total disagreed.
Fix / how to use it: see OrderLine.WithQuantity in Go and ShippingAddress::withLine2() in PHP. Note the PHP manual's warning: "readonly properties do not preclude interior mutability"; keep only immutable things (scalars, enums, other readonly values) inside readonly values.
Side-effect-free functions and closure of operations Must-know
In plain words: a value's methods only calculate and return an answer; and where it fits, adding two moneys gives a money, so you can chain operations without new concepts.
Common misunderstanding: "Divide is just another operation." Money divided by 3 is not money (10.00 / 3 = 3.333...). Forcing it to be closed loses cents. The closed operation for "split money" is allocation, which returns parts that add back to the whole.
Definition: Evans, Side-Effect-Free Functions: "Place as much of the logic of the program as possible into functions, operations that return results with no observable side effects. Strictly segregate commands ... into very simple operations that do not return domain information." And "All operations of a value object should be side-effect-free functions." Closure of Operations: "Where it fits, define an operation whose return type is the same as the type of its argument(s) ... This pattern is most often applied to the operations of a value object."
Splitting a 10.00 EUR voucher across three lines
1 float: 10.00 / 3 = 3.3333 -> round -> 3.33 x 3 = 9.99 one cent lost
2 Allocate: 1000 minor, ratios 1,1,1 -> 333, 333, 333, remainder 1
3 remainder goes to the first part -> 334, 333, 333 sum = 1000
4 Property: for any amount and ratios, sum(parts) == amount (tested 10,000 times)Real scenario: VAT at 9% on 12.50 EUR is 1.125 EUR, which must round to a minor unit by a stated rule (we use half away from zero); a shipping fee split across sellers in a marketplace; an instalment plan of 1,000,000 IRR in 3 payments.
| Operation | Closed? | Signature | Note |
|---|---|---|---|
| Add / Subtract | Yes | Money x Money -> Money | Same currency or error |
| Multiply by Quantity | Half-closed | Money x Quantity -> Money | Argument differs, return matches |
| Percentage of | Half-closed | Money x Percentage -> Money | Must name the rounding rule |
| Allocate | Closed over the set | Money x ratios -> []Money | Sum of parts equals the whole |
| Divide | No | Money / int -> ? | Do not provide it |
| Compare | Not closed (returns bool) | Money x Money -> bool | Same currency only |
Fix / how to use it: Money.Add, Sub, Times(Quantity), PercentOf(Percentage), Allocate(ratios...) in Go; the same in PHP. Commands (Order.Place) return only an error, never domain data.
Whole values and conceptual contours Important
In plain words: group the attributes that mean something together into one type (amount + currency, start + end), and cut your types where the business draws lines, not where the database does.
Common misunderstanding: "Small types are over-engineering; a string is fine." A string for a phone number accepts "hello"; a float for a price adds EUR to IRR. Fowler: replacing primitives with value objects "makes variables and parameters more explicit (with type checking when the language supports it), a natural focus for validation, and avoiding inapplicable behaviors (such as doing arithmetic on integer id numbers)." The opposite smell is primitive obsession (see Code Smells).
Definition: a whole value represents one complete concept of the domain. Evans's Conceptual Contours: "Decompose design elements (operations, interfaces, classes, and aggregates) into cohesive units, taking into consideration your intuition of the important divisions in the domain." He warns against cutting too fine as well: "Half of a uranium atom is not uranium."
Signature drift, before and after whole values
1 func Charge(amount float64, currency string, customerID string, orderID string)
2 Charge(12.5, "eur", orderID, customerID) // compiles; ids swapped; currency lower-case
3 func Charge(total Money, customer CustomerID, order OrderID)
4 Charge(total, order, customer) // compile error: cannot use OrderID as CustomerIDReal scenario (where the contour runs):
| Too fine (primitives) | Whole value | Too coarse |
|---|---|---|
amount float64, currency string | Money | OrderTotals with 14 optional fields |
start, end time.Time | DateRange with Contains, Overlaps | Campaign used just for its dates |
phone string | PhoneNumber (E.164) | ContactInfo mixing phone, e-mail, consent |
city, postal, line1 ... | ShippingAddress | Customer carrying an address it does not own |
rate int // percent? bp? | Percentage in basis points | PricingRule blob |
Fix / how to use it: introduce one value at a time where bugs happen (money first, then ids, then contact data). Vernon calls widely shared ones Standard Types (currencies, country codes); in our code Currency and OrderStatus play that role.
Equality and hashing pitfalls Must-know
In plain words: value equality is only as good as the fields you compare; floats, time zones, letter variants and digit scripts make "the same" values look different (or different ones look the same).
Common misunderstanding: "== is enough." In Go, == on a struct holding a time.Time compares location and monotonic clock; on a struct holding a slice it does not compile; through an interface holding such a struct it panics at runtime. In PHP, == compares two objects "if they have the same attributes and values (values are compared with ==), and are instances of the same class", with PHP's loose == rules for each property.
Definition: a value's equality must be (1) defined on a canonical form, produced at construction, and (2) consistent with hashing (Go map keys; PHP array keys need a string form). Fowler: "values override the equality method (and thus hash) while entities usually don't."
Five ways "equal" values compare unequal
1 0.1 + 0.2 == 0.3 (float64 variables) -> false (0.30000000000000004) use int64 minor units
2 t1 == t2 for the same instant -> false if one is Asia/Tehran, one UTC; use Equal or store UTC civil date
3 "۰۹۱۲۱۲۳۴۵۶۷" vs "09121234567" -> different bytes; map Persian digits explicitly
4 "علي" (U+064A) vs "علی" (U+06CC) -> NFC and NFKC keep them different; fold explicitly if the domain says so
5 "Sara@Example.com" vs "Sara@example.com" -> lower-case the domain at constructionThe Go manual says it directly: "the Go == operator compares not just the time instant but also the Location and the monotonic clock reading ... In general, prefer t.Equal(u) to t == u". The PHP manual on floats: "Floating-point numbers have limited precision." Unicode Standard Annex 15 promises that "When implementations keep strings in a normalized form, they can be assured that equivalent strings have a unique binary representation", but Arabic Yeh (U+064A) and Farsi Yeh (U+06CC), Arabic Kaf (U+0643) and Keheh (U+06A9), and the Persian digits are not equivalent under NFC or NFKC (we checked with Python's unicodedata); a Persian-language system must decide and apply its own folding. Text-level details: Bits, Bytes & Text Encoding.
| Pitfall | Go | PHP | Remedy in the value |
|---|---|---|---|
| Float amounts | float64 sums drift | float sums drift | Integer minor units; parse decimals as strings |
| Time values | == compares Location + monotonic | DateTime == compares instants; === instances | Store UTC or civil date fields; compare with Equal |
| Non-comparable fields | Slice/map field: compile error; via any: runtime panic | n/a | Keep values flat; or write Equals and a string key |
| Case and whitespace | Byte-wise strings | Byte-wise strings | Normalise in the constructor |
| Persian/Arabic digits and letters | Runes differ | Code points differ | Explicit mapping table at construction |
| Enum vs string | Typed const vs raw string | Enum case vs 'placed' | Parse once at the edge |
Fix / how to use it: canonicalise in the constructor (PhoneNumber stores E.164, Email lower-cases the domain, DateRange stores UTC civil dates), then == (Go) or equals() (PHP) compares canonical forms. Test equality and map-key behaviour explicitly (tests).
Enums as value objects Important
In plain words: a status or a currency is a value with a fixed set of possibilities; make that set a type and put the related rules on it.
Common misunderstanding: "Enums are constants with names." In PHP, "Enums (both Pure Enums and Backed Enums) may contain methods, and may implement interfaces"; in Go a typed constant can have methods. That makes them full value objects with behaviour (CanCancel(), MinorUnits()).
Definition: an enumeration value object is a value type with a closed set of instances. PHP backed enums round-trip to storage: from() "will throw a ValueError" for an unknown scalar and tryFrom() "will return null". Go has no enum keyword; use a named type, iota constants starting at 1 (so the zero value is invalid), a String() method and a Parse function.
Status from storage
1 row.status = "plcaed" (legacy typo in the column)
2 PHP: OrderStatus::from('plcaed') -> ValueError: "plcaed" is not a valid backing value for enum App\Domain\Sales\OrderStatus
3 Go: ParseOrderStatus("plcaed") -> error: unknown order status "plcaed"
4 Either way the bad row fails at the boundary, not halfway through a refund.Real scenario: order states, payment methods, currencies, shipping speeds, tax classes. Vernon's TOC calls the persistence case "ORM and Enum-as-State Objects".
| Need | PHP 8.4 | Go | Laravel / SQL |
|---|---|---|---|
| Closed set | enum OrderStatus: string | type OrderStatus uint8 + iota | CHECK (status IN (...)) or a PostgreSQL enum type |
| Behaviour | Methods on the enum | Methods on the type | n/a |
| Parse | from / tryFrom | ParseOrderStatus | Eloquent enum cast 'status' => OrderStatus::class |
| Array of enums | AsEnumCollection::of(...) | []OrderStatus | JSON column |
Fix / how to use it: Currency (PHP enum with minorUnits(), Go struct from a registry), OrderStatus (PHP enum with canCancel(), Go typed constant with CanCancel()).
Entities composed of values; the OrderLine debate Important
In plain words: a good entity is a thin shell of identity and lifecycle around many values; the open question is usually whether its parts (like order lines) are values or small entities.
Common misunderstanding: "Anything stored in its own table must be an entity." Storage does not decide. Vernon notes that an ORM may force a collection of values into rows with ids ("it must model collections of Values as database entities"), but that is a persistence detail.
Definition: an entity holds value objects as attributes and replaces them as a whole. A part of an entity is a value when it can be replaced completely and has no lifecycle of its own; it is a local entity when something must follow it individually over time.
The OrderLine debate:
| Question | If "no" -> value | If "yes" -> local entity |
|---|---|---|
| Can two lines have the same SKU? | Merge them; SKU identifies the line in its order | Need a line id |
| Does a line have its own lifecycle (backordered, picked, returned)? | Status lives on the Order or in Fulfilment | Line carries state transitions |
| Do other contexts refer to a specific line? | Refer to (order id, SKU) | Need a stable line id |
| Is a line edited in place (price override with audit)? | Replace the line | Track changes to that line |
Same domain, two contexts, two answers
1 Sales: "2 x SKU-42 at 12.50" -> value; change qty = replace line
2 Fulfilment: line SKU-42 qty 2 -> 1 picked, 1 backordered, then 1 returned
3 -> ShipmentItem is an entity in Fulfilment with its own id and state
4 Sales keeps OrderLine as a value; Fulfilment builds its own model from OrderPlacedV1Fix / how to use it: in Sales, OrderLine is a value identified by SKU within its order, as in the code here. The Aggregates & Factories chapter makes a slightly different choice in its Go code: the line is an unexported internal entity of the Order root, also keyed by SKU, which the root mutates in place. Both keep the line unreachable from outside and keyed by SKU; the difference is replace-the-value (this page) versus mutate-through-the-root (that page). Either is defensible inside one aggregate; pick one per codebase. Fulfilment owns per-item lifecycle.
Mechanics
Persistence mapping options Must-know
Fowler's Embedded Value "maps the values of an object to fields in the record of the object's owner" ("no sane person would want a table of money values"); Serialized LOB "Saves a graph of objects by serializing them into a single large object (LOB), which it stores in a database field"; Dependent Mapping "Has one class perform the database mapping for a child class". A fourth option is a single-column type.
| Option | Use for | Query and constraints | Migration cost | Laravel | Go |
|---|---|---|---|---|---|
| Embedded columns | Money, DateRange, small addresses | Full SQL, indexes, CHECK | Column per field | CastsAttributes::set returns an array | Repository maps fields |
JSON / jsonb column | Addresses, settings, snapshots | jsonb operators; weak constraints | Old rows keep old shapes | Castable::castUsing, AsArrayObject | json.Marshal to []byte |
| Dependent table | Collections of values | Full SQL; key without surrogate | Replace set = delete + insert | Second model, mapped by repository | Second query, mapped by repository |
| Single column | Ids, e-mails, enums | Domain/CHECK | Trivial | Enum cast, custom cast | sql.Scanner + driver.Valuer |
The schema for our running example, PostgreSQL, using all four:
-- PostgreSQL. Four mapping styles for value objects in one schema:
-- single column (id, status), embedded columns (Money), JSON (address), dependent table (lines).
CREATE DOMAIN currency_code AS char(3) CHECK (VALUE ~ '^[A-Z]{3}$');
CREATE TABLE orders (
id uuid PRIMARY KEY, -- OrderID (UUIDv7, generated by the app)
customer_id text NOT NULL, -- reference to Identity, not a foreign key
currency currency_code NOT NULL, -- Currency, embedded
status text NOT NULL CHECK (status IN ('draft','placed','paid','dispatched','cancelled')),
-- ShippingAddress as JSON: one value, read and written whole
ship_to jsonb,
-- Total cached for reports; the model derives it, the DB only stores it
total_minor bigint NOT NULL DEFAULT 0, -- Money, embedded: amount ...
total_currency currency_code NOT NULL, -- ... and currency, side by side
placed_at timestamptz,
version integer NOT NULL DEFAULT 0
);
-- Collection of value objects: a dependent table with no surrogate id.
-- The identity of a row is (order, sku): it exists only inside its order.
CREATE TABLE order_lines (
order_id uuid NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
sku text NOT NULL,
quantity integer NOT NULL CHECK (quantity BETWEEN 1 AND 50),
unit_price_minor bigint NOT NULL CHECK (unit_price_minor >= 0),
PRIMARY KEY (order_id, sku)
);PostgreSQL's domain type is a database-level value constraint: "A domain is essentially a data type with optional constraints (restrictions on the allowed set of values)." A shorter example:
CREATE DOMAIN postal_code_ir AS char(10) CHECK (VALUE ~ '^[0-9]{10}$');
CREATE DOMAIN money_minor AS bigint;
-- Re-validate legacy rows before turning on a stricter VO
SELECT id, ship_to->>'postal_code' AS pc
FROM orders
WHERE ship_to IS NOT NULL
AND (ship_to->>'postal_code') !~ '^[0-9]{10}$';
-- Totals per currency: embedded Money columns make this trivial
SELECT total_currency, sum(total_minor) AS minor
FROM orders WHERE status = 'placed'
GROUP BY total_currency;Rehydration. When loading, rebuild every value through its constructor (so legacy bad rows fail loudly) but rebuild the entity through a dedicated Rehydrate function that sets state without replaying creation rules ("an order must start as draft" does not apply to a stored dispatched order). Go's database/sql Scanner contract: "An error should be returned if the value cannot be stored without loss of information", and "Reference types such as []byte are only valid until the next call to Scan and should not be retained."
Values at the edge: DTOs, events and messages Must-know
Inside the bounded context, values are types. Outside, they are a published language: a documented JSON or Protobuf shape. Do not serialise domain objects directly; map them to DTOs, because renaming a private field must not break a client, and because consumers in other languages cannot run your constructor.
OrderPlaced crossing from Sales to Billing and Fulfilment
1 Sales: Order.Place(now) -> builds OrderPlacedV1 DTO from values
2 JSON: {"order_id":"0190f3c2-...","total":{"amount_minor":2500,"currency":"EUR","formatted":"25.00 EUR"}, ...}
3 Outbox row committed with the order (one transaction)
4 Billing: decodes JSON -> its own Money value (same rules, its own code) -> Invoice entity
5 Fulfilment: decodes -> ShipmentItem entities with their own ids
Values never travel as objects; identities travel as strings; amounts as integers + currency.| Rule | Why |
|---|---|
| Money as integer minor units + currency code, plus an optional formatted string | JavaScript numbers are IEEE 754 doubles; floats drift |
| Ids as strings | UUIDs exceed 53-bit integers; clients must not do arithmetic on ids |
| Enums as lower-case strings, documented list | Adding a case is a contract change for consumers |
| Times as RFC 3339 UTC instants | Time zones are presentation |
| Events are immutable values | Evans: "Domain events are ordinarily immutable, as they are a record of something in the past." |
Version the event type (OrderPlacedV1) | Shape changes must be explicit (Message Design) |
Laravel's documentation suggests that value objects in models "implement the Illuminate\Contracts\Support\Arrayable and JsonSerializable interfaces" if models are serialised; that is fine for internal arrays, but the API contract should still be an explicit JsonResource. The integration-event side is covered in Domain Events vs Integration Events and reliable publishing in Outbox.
Errors you will meet
| Where | Message (verbatim) | Meaning |
|---|---|---|
| Go compiler | invalid operation: a == b (struct containing []string cannot be compared) | A value with a slice field is not comparable |
| Go runtime | panic: runtime error: hash of unhashable type main.Tags | Non-comparable value used as a key via any |
| PHP | Error: Cannot modify readonly property Test::$prop (manual example) | Writing to a readonly property |
| PHP 8.4 | Cannot modify private(set) property Manager::$calls from global scope (manual example) | Writing past asymmetric visibility |
| PHP enums | "%s" is not a valid backing value for enum %s (php-src zend_enum.c, ValueError) | from() with an unknown scalar |
| Laravel custom cast (docs example) | The given value is not an Address instance. | set received a non-VO |
| This page's Go | invalid quantity: 60 not in 1..50 | Invariant broken by an operation |
| This page's Go | currency mismatch: EUR + USD | Closure guarded by currency |
Go
The module is docs/snippets/ddd/entities-value-objects/go, standard library only; gofmt -l . is empty, go vet ./... and go test ./... pass (output in the Lab).
Before: primitives everywhere
Compiles, runs, and lets every bug on this page through:
// Package before shows the shape this page argues against: an entity made of
// primitives with public fields. It compiles and "works"; it is bad design.
package before
// Order has no invariants of its own. Every caller must remember them.
type Order struct {
ID int64 // auto-increment: unknown until INSERT
CustomerID string // could be passed where an order id is expected
Status string // "placed", "Placed", "PLACED", "plcaed"...
Total float64 // 0.1 + 0.2 != 0.3
Currency string // may disagree with the lines
City string // address split into loose fields
PostalCode string // "۱۲۳۴۵-۶۷۸۹۰" or "1234567890"?
Phone string // "0912...", "+98912...", "۰۹۱۲..."
Lines []Line
}
type Line struct {
SKU string
Quantity int // 0? -3?
UnitPrice float64 // in which currency?
}
// AddLine trusts its input and recomputes the total with floats.
func (o *Order) AddLine(sku string, qty int, price float64) {
o.Lines = append(o.Lines, Line{SKU: sku, Quantity: qty, UnitPrice: price})
o.Total += float64(qty) * price
}Value objects
Currency and Money: integer minor units, ISO 4217 exponents, closed Add, half-closed Times and PercentOf, Allocate that never loses a unit, and parsing without float64:
package sales
import "fmt"
// Currency is a value object: an ISO 4217 code plus its minor-unit exponent.
// Both fields are comparable, so Currency can be compared with == and used as
// a map key.
type Currency struct {
code string
minor int
}
// Exponents copied from the ISO 4217 list one (SIX, published 2026-09-17).
var currencies = map[string]Currency{
"EUR": {"EUR", 2},
"USD": {"USD", 2},
"IRR": {"IRR", 2}, // ISO lists 2; most Iranian systems price in whole rials (see the page)
"JPY": {"JPY", 0},
"KWD": {"KWD", 3},
}
// CurrencyOf returns the Currency for an ISO code or an error.
func CurrencyOf(code string) (Currency, error) {
c, ok := currencies[code]
if !ok {
return Currency{}, fmt.Errorf("%w: unknown currency %q", ErrInvalidMoney, code)
}
return c, nil
}
// MustCurrency is for constants in tests and examples only.
func MustCurrency(code string) Currency {
c, err := CurrencyOf(code)
if err != nil {
panic(err)
}
return c
}
func (c Currency) Code() string { return c.code }
// MinorUnits is the number of decimal places of the minor unit (cents = 2).
func (c Currency) MinorUnits() int { return c.minor }
func (c Currency) String() string { return c.code }package sales
import (
"fmt"
"math"
"strings"
)
// Money is an amount in minor units (cents, fils, rials...) and a currency.
// Integers, not floats: 0.1 + 0.2 must equal 0.3.
// Fields are unexported; the only way in is a constructor that validates.
type Money struct {
minor int64
currency Currency
}
// NewMoney builds Money from minor units ("2250 EUR cents" = 22.50 EUR).
func NewMoney(minor int64, currency Currency) (Money, error) {
if currency.code == "" {
return Money{}, fmt.Errorf("%w: currency is required", ErrInvalidMoney)
}
return Money{minor: minor, currency: currency}, nil
}
// Zero is the neutral element for Add in a currency.
func Zero(currency Currency) Money { return Money{currency: currency} }
func (m Money) Minor() int64 { return m.minor }
func (m Money) Currency() Currency { return m.currency }
func (m Money) IsZero() bool { return m.minor == 0 }
func (m Money) IsNegative() bool { return m.minor < 0 }
// Add is closed over Money: Money + Money = Money. Different currencies fail.
func (m Money) Add(o Money) (Money, error) {
if m.currency != o.currency {
return Money{}, fmt.Errorf("%w: %s + %s", ErrCurrencyMismatch, m.currency, o.currency)
}
if (o.minor > 0 && m.minor > math.MaxInt64-o.minor) || (o.minor < 0 && m.minor < math.MinInt64-o.minor) {
return Money{}, fmt.Errorf("%w: overflow", ErrInvalidMoney)
}
return Money{minor: m.minor + o.minor, currency: m.currency}, nil
}
// Sub is Add of the negation.
func (m Money) Sub(o Money) (Money, error) {
return m.Add(Money{minor: -o.minor, currency: o.currency})
}
// Times multiplies by a Quantity: unit price x quantity = line total.
func (m Money) Times(q Quantity) (Money, error) {
n := int64(q.Int())
if n != 0 && (m.minor > math.MaxInt64/n || m.minor < math.MinInt64/n) {
return Money{}, fmt.Errorf("%w: overflow", ErrInvalidMoney)
}
return Money{minor: m.minor * n, currency: m.currency}, nil
}
// PercentOf applies a Percentage and rounds half away from zero to the minor unit.
func (m Money) PercentOf(p Percentage) Money {
num := m.minor * int64(p.BasisPoints())
q, r := num/10000, num%10000
if r*2 >= 10000 {
q++
} else if r*2 <= -10000 {
q--
}
return Money{minor: q, currency: m.currency}
}
// Allocate splits m by ratios without losing a single minor unit: the
// remainder goes one unit at a time to the first parts. Division of money
// is not closed (10 / 3 is not money); allocation is.
func (m Money) Allocate(ratios ...int) ([]Money, error) {
total := 0
for _, r := range ratios {
if r < 0 {
return nil, fmt.Errorf("%w: negative ratio", ErrInvalidMoney)
}
total += r
}
if total == 0 {
return nil, fmt.Errorf("%w: ratios sum to zero", ErrInvalidMoney)
}
parts := make([]Money, len(ratios))
remainder := m.minor
for i, r := range ratios {
share := m.minor * int64(r) / int64(total)
parts[i] = Money{minor: share, currency: m.currency}
remainder -= share
}
for i := 0; remainder != 0; i = (i + 1) % len(parts) {
step := int64(1)
if remainder < 0 {
step = -1
}
parts[i].minor += step
remainder -= step
}
return parts, nil
}
// Equals is value equality. Money is also comparable with ==, because every
// field is comparable; Equals exists for readability and for symmetry with PHP.
func (m Money) Equals(o Money) bool { return m == o }
// String formats with the currency's exponent: "22.50 EUR", "1500 JPY".
func (m Money) String() string {
e := m.currency.minor
sign := ""
v := m.minor
if v < 0 {
sign, v = "-", -v
}
if e == 0 {
return fmt.Sprintf("%s%d %s", sign, v, m.currency)
}
p := int64(math.Pow10(e))
frac := fmt.Sprintf("%0*d", e, v%p)
return fmt.Sprintf("%s%d.%s %s", sign, v/p, frac, m.currency)
}
// ParseMoney reads "22.50" in a currency without going through float64.
func ParseMoney(decimal string, currency Currency) (Money, error) {
s := strings.TrimSpace(decimal)
neg := strings.HasPrefix(s, "-")
s = strings.TrimPrefix(s, "-")
whole, frac, _ := strings.Cut(s, ".")
if whole == "" || len(frac) > currency.minor {
return Money{}, fmt.Errorf("%w: %q has more than %d decimals", ErrInvalidMoney, decimal, currency.minor)
}
frac += strings.Repeat("0", currency.minor-len(frac))
var v int64
for _, ch := range whole + frac {
if ch < '0' || ch > '9' {
return Money{}, fmt.Errorf("%w: %q is not a number", ErrInvalidMoney, decimal)
}
if v > (math.MaxInt64-int64(ch-'0'))/10 {
return Money{}, fmt.Errorf("%w: overflow", ErrInvalidMoney)
}
v = v*10 + int64(ch-'0')
}
if neg {
v = -v
}
return NewMoney(v, currency)
}Quantity and Percentage (basis points, so 12.5% is exact):
package sales
import "fmt"
// Quantity is a positive count of units, capped by a business rule.
type Quantity struct{ n int }
// MaxQuantityPerLine is a Sales policy, not a technical limit.
const MaxQuantityPerLine = 50
func NewQuantity(n int) (Quantity, error) {
if n < 1 || n > MaxQuantityPerLine {
return Quantity{}, fmt.Errorf("%w: %d not in 1..%d", ErrInvalidQuantity, n, MaxQuantityPerLine)
}
return Quantity{n: n}, nil
}
func (q Quantity) Int() int { return q.n }
// Add is closed over Quantity but must re-check the invariant.
func (q Quantity) Add(o Quantity) (Quantity, error) { return NewQuantity(q.n + o.n) }package sales
import "fmt"
// Percentage is stored in basis points (1% = 100 bp) so 12.5% is exact.
type Percentage struct{ bp int }
func NewPercentage(basisPoints int) (Percentage, error) {
if basisPoints < 0 || basisPoints > 10000 {
return Percentage{}, fmt.Errorf("%w: %d bp not in 0..10000", ErrInvalidPercent, basisPoints)
}
return Percentage{bp: basisPoints}, nil
}
func (p Percentage) BasisPoints() int { return p.bp }
func (p Percentage) String() string { return fmt.Sprintf("%d.%02d%%", p.bp/100, p.bp%100) }Email and the Iranian mobile PhoneNumber (E.164 canonical form; Persian and Arabic-Indic digits mapped explicitly; Iran's country code 98 and national prefix 0 as in Google's libphonenumber metadata, mobile national numbers being 10 digits starting with 9):
package sales
import (
"fmt"
"strings"
)
// Email is normalised once, at construction: trimmed and lower-cased domain.
// The local part is kept as typed (RFC 5321 lets servers treat it as
// case-sensitive), so two Emails are equal only if the normalised forms are.
type Email struct{ value string }
func NewEmail(raw string) (Email, error) {
s := strings.TrimSpace(raw)
local, domain, ok := strings.Cut(s, "@")
if !ok || local == "" || domain == "" || strings.ContainsAny(s, " \t\r\n") ||
strings.Contains(domain, "@") || !strings.Contains(domain, ".") || len(s) > 254 {
return Email{}, fmt.Errorf("%w: %q", ErrInvalidEmail, raw)
}
return Email{value: local + "@" + strings.ToLower(domain)}, nil
}
func (e Email) String() string { return e.value }package sales
import (
"fmt"
"strings"
)
// PhoneNumber is an Iranian mobile number stored in E.164 form (+989xxxxxxxxx).
// Accepted inputs: 09121234567, 9121234567, +989121234567, 00989121234567,
// with spaces or dashes, and with Persian (U+06F0..U+06F9) or Arabic-Indic
// (U+0660..U+0669) digits. Unicode normalisation (NFC/NFKC) does NOT map those
// digits to ASCII, so the mapping is explicit.
type PhoneNumber struct{ e164 string }
func NewIranianMobile(raw string) (PhoneNumber, error) {
var b strings.Builder
for _, r := range raw {
switch {
case r >= '0' && r <= '9':
b.WriteRune(r)
case r >= '۰' && r <= '۹':
b.WriteRune('0' + (r - '۰'))
case r >= '٠' && r <= '٩':
b.WriteRune('0' + (r - '٠'))
case r == '+' && b.Len() == 0:
b.WriteString("00")
case r == ' ' || r == '-' || r == '(' || r == ')':
// separators are presentation, not data
default:
return PhoneNumber{}, fmt.Errorf("%w: unexpected %q in %q", ErrInvalidPhone, r, raw)
}
}
d := b.String()
switch {
case strings.HasPrefix(d, "0098"):
d = d[4:]
case strings.HasPrefix(d, "98") && len(d) == 12:
d = d[2:]
case strings.HasPrefix(d, "0"):
d = d[1:] // national prefix 0
}
// National significant number for mobiles: 10 digits starting with 9.
if len(d) != 10 || d[0] != '9' {
return PhoneNumber{}, fmt.Errorf("%w: %q", ErrInvalidPhone, raw)
}
return PhoneNumber{e164: "+98" + d}, nil
}
func (p PhoneNumber) E164() string { return p.e164 }
// National renders the format people type in Iran: 0912 123 4567.
func (p PhoneNumber) National() string {
n := "0" + p.e164[3:]
return n[:4] + " " + n[4:7] + " " + n[7:]
}ShippingAddress collects every problem; DateRange avoids time.Time in its fields so == is safe:
package sales
import (
"fmt"
"strings"
)
// ShippingAddress is a value object: two parcels to the same address are
// indistinguishable, and "changing the address" means replacing it.
type ShippingAddress struct {
recipient string
line1 string
line2 string
city string
province string
postalCode string // Iran: 10 digits, written 12345-67890
country string // ISO 3166-1 alpha-2
phone PhoneNumber
}
// AddressInput is a plain struct so the constructor call stays readable.
type AddressInput struct {
Recipient, Line1, Line2, City, Province, PostalCode, Country string
Phone PhoneNumber
}
// NewShippingAddress collects every problem instead of stopping at the first,
// because a form needs all of them at once.
func NewShippingAddress(in AddressInput) (ShippingAddress, error) {
var problems []string
req := func(name, v string) string {
v = strings.TrimSpace(v)
if v == "" {
problems = append(problems, name+" is required")
}
return v
}
a := ShippingAddress{
recipient: req("recipient", in.Recipient),
line1: req("line1", in.Line1),
line2: strings.TrimSpace(in.Line2),
city: req("city", in.City),
province: strings.TrimSpace(in.Province),
country: strings.ToUpper(req("country", in.Country)),
phone: in.Phone,
}
pc := strings.NewReplacer("-", "", " ", "").Replace(in.PostalCode)
if a.country == "IR" && (len(pc) != 10 || strings.Trim(pc, "0123456789") != "") {
problems = append(problems, "postal code must be 10 digits in IR")
}
a.postalCode = pc
if in.Phone == (PhoneNumber{}) {
problems = append(problems, "phone is required")
}
if len(problems) > 0 {
return ShippingAddress{}, fmt.Errorf("%w: %s", ErrInvalidAddress, strings.Join(problems, "; "))
}
return a, nil
}
func (a ShippingAddress) Recipient() string { return a.recipient }
func (a ShippingAddress) Line1() string { return a.line1 }
func (a ShippingAddress) Line2() string { return a.line2 }
func (a ShippingAddress) City() string { return a.city }
func (a ShippingAddress) Province() string { return a.province }
func (a ShippingAddress) PostalCode() string { return a.postalCode }
func (a ShippingAddress) Country() string { return a.country }
func (a ShippingAddress) Phone() PhoneNumber { return a.phone }package sales
import (
"fmt"
"time"
)
// DateRange is a half-open interval [start, end) of calendar days.
// Inputs are converted to UTC and stored as civil dates (year, month, day),
// not as time.Time, because time.Time's == compares the Location and the
// monotonic reading too.
type DateRange struct {
startY, endY int
startM, endM time.Month
startD, endD int
}
func NewDateRange(start, end time.Time) (DateRange, error) {
r := DateRange{}
r.startY, r.startM, r.startD = start.UTC().Date()
r.endY, r.endM, r.endD = end.UTC().Date()
// Compare the days, not the instants: 09:00 and 17:00 of one day is empty.
if !r.Start().Before(r.End()) {
return DateRange{}, fmt.Errorf("%w: start %s is not before end %s", ErrInvalidRange,
r.Start().Format(time.DateOnly), r.End().Format(time.DateOnly))
}
return r, nil
}
func (r DateRange) Start() time.Time {
return time.Date(r.startY, r.startM, r.startD, 0, 0, 0, 0, time.UTC)
}
func (r DateRange) End() time.Time { return time.Date(r.endY, r.endM, r.endD, 0, 0, 0, 0, time.UTC) }
// Contains is a side-effect-free query.
func (r DateRange) Contains(t time.Time) bool {
u := t.UTC()
return !u.Before(r.Start()) && u.Before(r.End())
}
// Overlaps is how a promotion calendar avoids two campaigns on one day.
func (r DateRange) Overlaps(o DateRange) bool {
return r.Start().Before(o.End()) && o.Start().Before(r.End())
}OrderID (UUIDv7 per RFC 9562), CustomerID, and the OrderStatus enum:
package sales
import (
"crypto/rand"
"encoding/hex"
"fmt"
"strings"
"time"
)
// OrderID is the identity of an Order, typed so it cannot be confused with a
// CustomerID or a raw string. The value is a UUIDv7 (RFC 9562, section 5.7):
// 48-bit Unix milliseconds, version 7, variant 10, random bits.
type OrderID struct{ uuid [16]byte }
// NewOrderID is generated by the application, before the database sees the
// order, so the id can be the idempotency key and go into events.
func NewOrderID(now time.Time) OrderID {
var u [16]byte
if _, err := rand.Read(u[6:]); err != nil {
panic(err) // crypto/rand.Read does not fail on supported platforms
}
ms := uint64(now.UnixMilli())
for i := 0; i < 6; i++ {
u[i] = byte(ms >> (40 - 8*i))
}
u[6] = (u[6] & 0x0F) | 0x70 // version 7
u[8] = (u[8] & 0x3F) | 0x80 // variant 10
return OrderID{uuid: u}
}
// ParseOrderID accepts the canonical 8-4-4-4-12 form, any case.
func ParseOrderID(s string) (OrderID, error) {
var id OrderID
h := strings.ReplaceAll(s, "-", "")
if len(s) != 36 || len(h) != 32 {
return id, fmt.Errorf("%w: %q", ErrInvalidOrderID, s)
}
if _, err := hex.Decode(id.uuid[:], []byte(h)); err != nil {
return OrderID{}, fmt.Errorf("%w: %q", ErrInvalidOrderID, s)
}
return id, nil
}
func (id OrderID) IsZero() bool { return id == OrderID{} }
func (id OrderID) String() string {
h := hex.EncodeToString(id.uuid[:])
return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32]
}
// CustomerID belongs to the Identity context; Sales only holds the reference.
type CustomerID struct{ value string }
func NewCustomerID(v string) CustomerID { return CustomerID{value: v} }
func (c CustomerID) String() string { return c.value }package sales
import "fmt"
// OrderStatus is an enumeration value object: a typed constant with
// behaviour, not a free string.
type OrderStatus uint8
const (
StatusDraft OrderStatus = iota + 1 // start at 1 so the zero value is invalid
StatusPlaced
StatusPaid
StatusDispatched
StatusCancelled
)
var statusNames = map[OrderStatus]string{
StatusDraft: "draft",
StatusPlaced: "placed",
StatusPaid: "paid",
StatusDispatched: "dispatched",
StatusCancelled: "cancelled",
}
func (s OrderStatus) String() string {
if n, ok := statusNames[s]; ok {
return n
}
return fmt.Sprintf("OrderStatus(%d)", uint8(s))
}
// ParseOrderStatus is the only way from a stored string back to the enum.
func ParseOrderStatus(v string) (OrderStatus, error) {
for s, n := range statusNames {
if n == v {
return s, nil
}
}
return 0, fmt.Errorf("unknown order status %q", v)
}
// CanCancel puts a rule on the value instead of in every caller.
func (s OrderStatus) CanCancel() bool { return s == StatusDraft || s == StatusPlaced }// Package sales is the Sales bounded context: the Order entity and the value
// objects it is built from. It depends on the standard library only.
package sales
import "errors"
// Sentinel errors let callers branch with errors.Is without parsing text.
var (
ErrInvalidMoney = errors.New("invalid money")
ErrCurrencyMismatch = errors.New("currency mismatch")
ErrInvalidQuantity = errors.New("invalid quantity")
ErrInvalidEmail = errors.New("invalid email")
ErrInvalidPhone = errors.New("invalid phone number")
ErrInvalidAddress = errors.New("invalid shipping address")
ErrInvalidRange = errors.New("invalid date range")
ErrInvalidPercent = errors.New("invalid percentage")
ErrInvalidOrderID = errors.New("invalid order id")
ErrOrderNotDraft = errors.New("order is not a draft")
ErrEmptyOrder = errors.New("order has no lines")
)The entity
OrderLine is a value; Order is the entity: pointer receiver, unexported state, intention-revealing methods, SameAs for identity equality, Lines() returns a copy, Rehydrate for the repository:
package sales
import "fmt"
// SKU is the Catalog context's product code, used in Sales as a value.
type SKU struct{ code string }
func NewSKU(code string) (SKU, error) {
if code == "" || len(code) > 32 {
return SKU{}, fmt.Errorf("invalid sku %q", code)
}
return SKU{code: code}, nil
}
func (s SKU) String() string { return s.code }
// OrderLine is modelled as a value object: "2 x SKU-42 at 12.50 EUR".
// Changing the quantity replaces the line. Inside the Order, lines are found
// by SKU (one line per SKU), so no line id is needed. If Fulfilment had to
// track each line through picking and returns, OrderLine would become an
// entity with a local id: see "The OrderLine debate" on the page.
type OrderLine struct {
sku SKU
quantity Quantity
unitPrice Money
}
func NewOrderLine(sku SKU, q Quantity, unitPrice Money) (OrderLine, error) {
if unitPrice.IsNegative() {
return OrderLine{}, fmt.Errorf("%w: negative unit price", ErrInvalidMoney)
}
return OrderLine{sku: sku, quantity: q, unitPrice: unitPrice}, nil
}
func (l OrderLine) SKU() SKU { return l.sku }
func (l OrderLine) Quantity() Quantity { return l.quantity }
func (l OrderLine) UnitPrice() Money { return l.unitPrice }
func (l OrderLine) Total() (Money, error) { return l.unitPrice.Times(l.quantity) }
// WithQuantity returns a new line; the receiver is untouched.
func (l OrderLine) WithQuantity(q Quantity) OrderLine {
l.quantity = q // l is a copy: value receiver
return l
}package sales
import (
"fmt"
"slices"
"time"
)
// Order is an entity: it is the same order from draft to dispatched although
// almost every attribute changes. Equality is by OrderID only.
// It is always used through a pointer, because it has a lifecycle.
type Order struct {
id OrderID
customer CustomerID
currency Currency
lines []OrderLine
shipTo ShippingAddress
status OrderStatus
placedAt time.Time
version int // optimistic-locking counter, set by the repository
}
// NewOrder starts the lifecycle. The id comes from outside (generated by the
// application service) so a retried request can reuse it.
func NewOrder(id OrderID, customer CustomerID, currency Currency) (*Order, error) {
if id.IsZero() {
return nil, ErrInvalidOrderID
}
return &Order{id: id, customer: customer, currency: currency, status: StatusDraft}, nil
}
func (o *Order) ID() OrderID { return o.id }
func (o *Order) Customer() CustomerID { return o.customer }
func (o *Order) Status() OrderStatus { return o.status }
func (o *Order) ShippingAddress() ShippingAddress { return o.shipTo }
func (o *Order) PlacedAt() time.Time { return o.placedAt }
func (o *Order) Version() int { return o.version }
// Lines returns a copy: callers cannot append to our slice behind our back.
func (o *Order) Lines() []OrderLine { return slices.Clone(o.lines) }
// SameAs is entity equality. Two *Order values loaded twice from the
// database are different pointers but the same order.
func (o *Order) SameAs(other *Order) bool { return other != nil && o.id == other.id }
// AddLine merges quantities for an SKU already in the order.
func (o *Order) AddLine(sku SKU, q Quantity, unitPrice Money) error {
if o.status != StatusDraft {
return fmt.Errorf("%w: status %s", ErrOrderNotDraft, o.status)
}
if unitPrice.Currency() != o.currency {
return fmt.Errorf("%w: order in %s, price in %s", ErrCurrencyMismatch, o.currency, unitPrice.Currency())
}
for i, l := range o.lines {
if l.SKU() == sku {
sum, err := l.Quantity().Add(q)
if err != nil {
return err
}
o.lines[i] = l.WithQuantity(sum) // replace the value, do not mutate it
return nil
}
}
line, err := NewOrderLine(sku, q, unitPrice)
if err != nil {
return err
}
o.lines = append(o.lines, line)
return nil
}
// ShipTo replaces the whole address value. There is no SetCity.
func (o *Order) ShipTo(a ShippingAddress) error {
if o.status != StatusDraft && o.status != StatusPlaced {
return fmt.Errorf("%w: cannot change address when %s", ErrOrderNotDraft, o.status)
}
o.shipTo = a
return nil
}
// Total is derived from the lines, never stored on its own in the model.
func (o *Order) Total() (Money, error) {
total := Zero(o.currency)
for _, l := range o.lines {
lt, err := l.Total()
if err != nil {
return Money{}, err
}
if total, err = total.Add(lt); err != nil {
return Money{}, err
}
}
return total, nil
}
// Place is a command: it changes state and returns only an error.
func (o *Order) Place(now time.Time) error {
if o.status != StatusDraft {
return fmt.Errorf("%w: status %s", ErrOrderNotDraft, o.status)
}
if len(o.lines) == 0 {
return ErrEmptyOrder
}
if o.shipTo == (ShippingAddress{}) {
return fmt.Errorf("%w: missing", ErrInvalidAddress)
}
o.status = StatusPlaced
o.placedAt = now.UTC()
return nil
}
// Rehydrate rebuilds an Order from storage without re-running creation rules.
// Only the repository should call it.
func Rehydrate(id OrderID, customer CustomerID, currency Currency, lines []OrderLine,
shipTo ShippingAddress, status OrderStatus, placedAt time.Time, version int) *Order {
return &Order{id: id, customer: customer, currency: currency, lines: slices.Clone(lines),
shipTo: shipTo, status: status, placedAt: placedAt, version: version}
}Persistence and the edge
Scanner/Valuer for single-column values, the repository for embedded columns, JSON and the dependent table (with an optimistic version check), and DTOs for HTTP and events:
package sales
import (
"database/sql/driver"
"fmt"
)
// OrderID and Email implement driver.Valuer and sql.Scanner so they can be
// passed to Exec and Scan directly. Multi-column values such as Money are
// mapped by the repository instead (Scanner reads one column).
func (id OrderID) Value() (driver.Value, error) { return id.String(), nil }
func (id *OrderID) Scan(src any) error {
var s string
switch v := src.(type) {
case string:
s = v
case []byte:
s = string(v) // copy: the driver owns v after Scan returns
default:
return fmt.Errorf("%w: cannot scan %T", ErrInvalidOrderID, src)
}
parsed, err := ParseOrderID(s)
if err != nil {
return err
}
*id = parsed
return nil
}
func (e Email) Value() (driver.Value, error) { return e.value, nil }
func (e *Email) Scan(src any) error {
var s string
switch v := src.(type) {
case string:
s = v
case []byte:
s = string(v)
default:
return fmt.Errorf("%w: cannot scan %T", ErrInvalidEmail, src)
}
parsed, err := NewEmail(s) // re-validate: the column may hold legacy rows
if err != nil {
return err
}
*e = parsed
return nil
}// Package store maps the Sales model to PostgreSQL with database/sql.
// It is the only place that knows about columns.
package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"academy/entities-value-objects/sales"
)
// ErrConflict means someone else saved the order first (version mismatch).
var ErrConflict = errors.New("order was modified concurrently")
type OrderRepository struct{ db *sql.DB }
func NewOrderRepository(db *sql.DB) *OrderRepository { return &OrderRepository{db: db} }
// addressRow is the JSON shape of ShippingAddress in the ship_to column.
// It is a persistence DTO; the value object keeps its fields private.
type addressRow struct {
Recipient string `json:"recipient"`
Line1 string `json:"line1"`
Line2 string `json:"line2,omitempty"`
City string `json:"city"`
Province string `json:"province,omitempty"`
PostalCode string `json:"postal_code"`
Country string `json:"country"`
Phone string `json:"phone"`
}
func toAddressRow(a sales.ShippingAddress) addressRow {
return addressRow{a.Recipient(), a.Line1(), a.Line2(), a.City(), a.Province(),
a.PostalCode(), a.Country(), a.Phone().E164()}
}
func fromAddressRow(r addressRow) (sales.ShippingAddress, error) {
phone, err := sales.NewIranianMobile(r.Phone)
if err != nil {
return sales.ShippingAddress{}, err
}
return sales.NewShippingAddress(sales.AddressInput{Recipient: r.Recipient, Line1: r.Line1,
Line2: r.Line2, City: r.City, Province: r.Province, PostalCode: r.PostalCode,
Country: r.Country, Phone: phone})
}
// Save writes the order row and replaces its lines in one transaction.
// Lines are values: delete-and-insert is the honest mapping of "replace".
// The version check is optimistic locking: Save succeeds once per loaded
// version, so reload with ByID before saving the same order again.
func (r *OrderRepository) Save(ctx context.Context, o *sales.Order) error {
total, err := o.Total()
if err != nil {
return err
}
var shipTo any // NULL until an address is set
if o.ShippingAddress() != (sales.ShippingAddress{}) {
b, err := json.Marshal(toAddressRow(o.ShippingAddress()))
if err != nil {
return err
}
shipTo = b
}
var placedAt any
if !o.PlacedAt().IsZero() {
placedAt = o.PlacedAt()
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() // no-op after Commit
res, err := tx.ExecContext(ctx, `
INSERT INTO orders (id, customer_id, currency, status, ship_to, total_minor, total_currency, placed_at, version)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9 + 1)
ON CONFLICT (id) DO UPDATE SET
status = EXCLUDED.status, ship_to = EXCLUDED.ship_to, total_minor = EXCLUDED.total_minor,
placed_at = EXCLUDED.placed_at, version = orders.version + 1
WHERE orders.version = $9`,
o.ID(), o.Customer().String(), total.Currency().Code(), o.Status().String(), shipTo,
total.Minor(), total.Currency().Code(), placedAt, o.Version())
if err != nil {
return fmt.Errorf("save order %s: %w", o.ID(), err)
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrConflict
}
if _, err := tx.ExecContext(ctx, `DELETE FROM order_lines WHERE order_id = $1`, o.ID()); err != nil {
return err
}
for _, l := range o.Lines() {
if _, err := tx.ExecContext(ctx,
`INSERT INTO order_lines (order_id, sku, quantity, unit_price_minor) VALUES ($1, $2, $3, $4)`,
o.ID(), l.SKU().String(), l.Quantity().Int(), l.UnitPrice().Minor()); err != nil {
return err
}
}
return tx.Commit()
}
// ByID rebuilds the entity and every value object, re-validating each one.
func (r *OrderRepository) ByID(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
var (
customer, currencyCode, status string
shipTo []byte
placedAt sql.NullTime
version int
)
err := r.db.QueryRowContext(ctx,
`SELECT customer_id, currency, status, ship_to, placed_at, version FROM orders WHERE id = $1`, id).
Scan(&customer, ¤cyCode, &status, &shipTo, &placedAt, &version)
if err != nil {
return nil, err
}
currency, err := sales.CurrencyOf(currencyCode)
if err != nil {
return nil, err
}
st, err := sales.ParseOrderStatus(status)
if err != nil {
return nil, err
}
var addr sales.ShippingAddress
if shipTo != nil {
var row addressRow
if err := json.Unmarshal(shipTo, &row); err != nil {
return nil, err
}
if addr, err = fromAddressRow(row); err != nil {
return nil, err
}
}
rows, err := r.db.QueryContext(ctx,
`SELECT sku, quantity, unit_price_minor FROM order_lines WHERE order_id = $1 ORDER BY sku`, id)
if err != nil {
return nil, err
}
defer rows.Close()
var lines []sales.OrderLine
for rows.Next() {
var (
code string
qty int
price int64
)
if err := rows.Scan(&code, &qty, &price); err != nil {
return nil, err
}
line, err := buildLine(code, qty, price, currency)
if err != nil {
return nil, fmt.Errorf("order %s line %s: %w", id, code, err)
}
lines = append(lines, line)
}
if err := rows.Err(); err != nil {
return nil, err
}
var placed time.Time
if placedAt.Valid {
placed = placedAt.Time
}
return sales.Rehydrate(id, sales.NewCustomerID(customer), currency, lines, addr, st, placed, version), nil
}
func buildLine(code string, qty int, price int64, c sales.Currency) (sales.OrderLine, error) {
sku, err := sales.NewSKU(code)
if err != nil {
return sales.OrderLine{}, err
}
q, err := sales.NewQuantity(qty)
if err != nil {
return sales.OrderLine{}, err
}
m, err := sales.NewMoney(price, c)
if err != nil {
return sales.OrderLine{}, err
}
return sales.NewOrderLine(sku, q, m)
}// Package api is the HTTP edge. It never exposes value objects directly:
// it maps them to DTOs whose JSON shape is a contract with clients.
package api
import (
"encoding/json"
"time"
"academy/entities-value-objects/sales"
)
// MoneyDTO sends minor units as an integer plus a decimal string for display.
// Never a JSON float: JavaScript numbers are IEEE 754 doubles.
type MoneyDTO struct {
AmountMinor int64 `json:"amount_minor"`
Currency string `json:"currency"`
Formatted string `json:"formatted"`
}
type OrderLineDTO struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
UnitPrice MoneyDTO `json:"unit_price"`
}
type OrderDTO struct {
ID string `json:"id"`
Status string `json:"status"`
Lines []OrderLineDTO `json:"lines"`
Total MoneyDTO `json:"total"`
PlacedAt *time.Time `json:"placed_at,omitempty"`
}
func moneyDTO(m sales.Money) MoneyDTO {
return MoneyDTO{AmountMinor: m.Minor(), Currency: m.Currency().Code(), Formatted: m.String()}
}
// FromOrder is the one-way mapping used by GET /orders/{id}.
func FromOrder(o *sales.Order) (OrderDTO, error) {
total, err := o.Total()
if err != nil {
return OrderDTO{}, err
}
dto := OrderDTO{ID: o.ID().String(), Status: o.Status().String(), Total: moneyDTO(total),
Lines: []OrderLineDTO{}}
for _, l := range o.Lines() {
dto.Lines = append(dto.Lines, OrderLineDTO{SKU: l.SKU().String(), Quantity: l.Quantity().Int(),
UnitPrice: moneyDTO(l.UnitPrice())})
}
if !o.PlacedAt().IsZero() {
t := o.PlacedAt()
dto.PlacedAt = &t
}
return dto, nil
}
// OrderPlacedV1 is the integration event Billing and Fulfilment consume.
// Values travel as primitives in a documented shape (published language),
// identities travel as strings.
type OrderPlacedV1 struct {
EventID string `json:"event_id"`
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
Total MoneyDTO `json:"total"`
ShipToCity string `json:"ship_to_city"`
OccurredAt time.Time `json:"occurred_at"`
}
func NewOrderPlacedV1(eventID string, o *sales.Order) ([]byte, error) {
total, err := o.Total()
if err != nil {
return nil, err
}
return json.Marshal(OrderPlacedV1{EventID: eventID, OrderID: o.ID().String(),
CustomerID: o.Customer().String(), Total: moneyDTO(total),
ShipToCity: o.ShippingAddress().City(), OccurredAt: o.PlacedAt()})
}Tests
Equality, closure, a property test of Allocate over 10,000 random cases with a fixed seed (math/rand/v2), a fuzz test that checks phone normalisation is idempotent, and entity identity tests:
package sales
import (
"errors"
"math/rand/v2"
"testing"
)
var eur = MustCurrency("EUR")
func eurCents(n int64) Money { m, _ := NewMoney(n, eur); return m }
func TestMoneyEqualityIsByValue(t *testing.T) {
a, b := eurCents(2250), eurCents(2250)
if a != b || !a.Equals(b) {
t.Fatal("two 22.50 EUR must be equal")
}
// Comparable values work as map keys: the value is the key.
seen := map[Money]int{a: 1}
if seen[b] != 1 {
t.Fatal("equal values must hash to the same key")
}
}
func TestAddIsClosedAndRejectsMixedCurrencies(t *testing.T) {
sum, err := eurCents(10).Add(eurCents(20))
if err != nil || sum != eurCents(30) {
t.Fatalf("0.10 + 0.20 = %v, %v", sum, err)
}
usd, _ := NewMoney(10, MustCurrency("USD"))
if _, err := eurCents(10).Add(usd); !errors.Is(err, ErrCurrencyMismatch) {
t.Fatalf("want ErrCurrencyMismatch, got %v", err)
}
}
func TestStringUsesTheCurrencyExponent(t *testing.T) {
jpy, _ := NewMoney(1500, MustCurrency("JPY"))
kwd, _ := NewMoney(1234, MustCurrency("KWD"))
for _, c := range []struct {
m Money
want string
}{{eurCents(2250), "22.50 EUR"}, {eurCents(-5), "-0.05 EUR"}, {jpy, "1500 JPY"}, {kwd, "1.234 KWD"}} {
if got := c.m.String(); got != c.want {
t.Errorf("got %q want %q", got, c.want)
}
}
}
func TestParseMoneyNeverUsesFloat(t *testing.T) {
m, err := ParseMoney("0.30", eur)
if err != nil || m.Minor() != 30 {
t.Fatalf("got %v %v", m, err)
}
if _, err := ParseMoney("1.234", eur); !errors.Is(err, ErrInvalidMoney) {
t.Fatal("EUR has two decimals")
}
}
// Property: allocation never creates or loses a minor unit, and no two
// parts differ by more than the ratio would explain plus one unit.
func TestAllocateConservesTotalProperty(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2)) // fixed seed: reproducible failures
for i := 0; i < 10_000; i++ {
amount := r.Int64N(2_000_000) - 1_000_000
n := 1 + r.IntN(6)
ratios := make([]int, n)
for j := range ratios {
ratios[j] = 1 + r.IntN(5)
}
parts, err := eurCents(amount).Allocate(ratios...)
if err != nil {
t.Fatal(err)
}
sum := Zero(eur)
for _, p := range parts {
sum, _ = sum.Add(p)
}
if sum != eurCents(amount) {
t.Fatalf("allocate(%d, %v) sums to %v", amount, ratios, sum)
}
}
}
func TestAllocateExample(t *testing.T) {
parts, _ := eurCents(1000).Allocate(1, 1, 1)
want := []Money{eurCents(334), eurCents(333), eurCents(333)}
for i := range want {
if parts[i] != want[i] {
t.Fatalf("part %d = %v, want %v", i, parts[i], want[i])
}
}
}
func TestPercentOfRoundsHalfAwayFromZero(t *testing.T) {
vat, _ := NewPercentage(900) // 9%
if got := eurCents(1250).PercentOf(vat); got != eurCents(113) { // 112.5 -> 113
t.Fatalf("got %v", got)
}
}package sales
import (
"errors"
"strings"
"testing"
"time"
)
func TestIranianMobileAcceptsEveryCommonSpelling(t *testing.T) {
inputs := []string{
"09121234567", "9121234567", "+989121234567", "00989121234567",
"0912 123 4567", "0912-123-4567",
"۰۹۱۲۱۲۳۴۵۶۷", // Persian digits
"٠٩١٢١٢٣٤٥٦٧", // Arabic-Indic digits
}
for _, in := range inputs {
p, err := NewIranianMobile(in)
if err != nil {
t.Fatalf("%q: %v", in, err)
}
if p.E164() != "+989121234567" || p.National() != "0912 123 4567" {
t.Fatalf("%q -> %s / %s", in, p.E164(), p.National())
}
}
for _, bad := range []string{"", "02112345678", "0912123456", "0912abc4567"} {
if _, err := NewIranianMobile(bad); !errors.Is(err, ErrInvalidPhone) {
t.Errorf("%q should be rejected, got %v", bad, err)
}
}
}
// Fuzz: whatever the input, a constructed number is canonical and
// re-parsing its E.164 form gives the same value (idempotent normalisation).
func FuzzIranianMobile(f *testing.F) {
f.Add("09121234567")
f.Add("۰۹۱۲۱۲۳۴۵۶۷")
f.Fuzz(func(t *testing.T, in string) {
p, err := NewIranianMobile(in)
if err != nil {
return
}
again, err := NewIranianMobile(p.E164())
if err != nil || again != p || !strings.HasPrefix(p.E164(), "+989") {
t.Fatalf("%q -> %q -> %v %v", in, p.E164(), again, err)
}
})
}
func TestAddressCollectsAllProblems(t *testing.T) {
_, err := NewShippingAddress(AddressInput{Country: "IR", PostalCode: "123"})
if !errors.Is(err, ErrInvalidAddress) {
t.Fatal(err)
}
for _, want := range []string{"recipient", "line1", "city", "postal code", "phone"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q does not mention %s", err, want)
}
}
}
func TestEmailNormalisesDomainOnly(t *testing.T) {
a, _ := NewEmail(" Sara@Example.COM ")
b, _ := NewEmail("Sara@example.com")
if a != b || a.String() != "Sara@example.com" {
t.Fatalf("%v vs %v", a, b)
}
}
func TestDateRangeIgnoresZoneAndMonotonicClock(t *testing.T) {
tehran := time.FixedZone("IRST", 3*3600+1800)
start := time.Date(2026, 3, 21, 1, 0, 0, 0, tehran) // 2026-03-20 21:30 UTC
a, _ := NewDateRange(start, start.Add(48*time.Hour))
b, _ := NewDateRange(start.UTC(), start.UTC().Add(48*time.Hour))
if a != b {
t.Fatal("same instants must give equal ranges")
}
if _, err := NewDateRange(start, start); !errors.Is(err, ErrInvalidRange) {
t.Fatal("empty range must fail")
}
morning := time.Date(2026, 3, 21, 9, 0, 0, 0, time.UTC)
if _, err := NewDateRange(morning, morning.Add(8*time.Hour)); !errors.Is(err, ErrInvalidRange) {
t.Fatal("two instants on the same day are an empty day range")
}
}
func TestQuantityInvariantHoldsAfterAdd(t *testing.T) {
q, _ := NewQuantity(30)
if _, err := q.Add(q); !errors.Is(err, ErrInvalidQuantity) {
t.Fatal("60 exceeds the per-line cap")
}
}
func TestOrderIDIsVersion7AndRoundTrips(t *testing.T) {
id := NewOrderID(time.UnixMilli(1_700_000_000_000))
s := id.String()
if s[14] != '7' || !strings.ContainsRune("89ab", rune(s[19])) {
t.Fatalf("not a v7/variant-10 uuid: %s", s)
}
back, err := ParseOrderID(s)
if err != nil || back != id {
t.Fatalf("round trip: %v %v", back, err)
}
var scanned OrderID
if err := scanned.Scan([]byte(s)); err != nil || scanned != id {
t.Fatalf("scan: %v %v", scanned, err)
}
v, _ := id.Value()
if v != s {
t.Fatalf("value: %v", v)
}
}
func TestOrderIDsSortByCreationTime(t *testing.T) {
a := NewOrderID(time.UnixMilli(1_700_000_000_000))
b := NewOrderID(time.UnixMilli(1_700_000_000_001))
if !(a.String() < b.String()) {
t.Fatal("UUIDv7 strings must sort by millisecond")
}
}
func TestStatusRoundTripAndRule(t *testing.T) {
s, err := ParseOrderStatus("placed")
if err != nil || s != StatusPlaced || !s.CanCancel() || StatusDispatched.CanCancel() {
t.Fatal("status rules")
}
var zero OrderStatus
if zero.String() != "OrderStatus(0)" {
t.Fatal("zero value must be visibly invalid")
}
}package sales
import (
"errors"
"testing"
"time"
)
func draftOrder(t *testing.T) *Order {
t.Helper()
o, err := NewOrder(NewOrderID(time.Now()), NewCustomerID("cus-7"), eur)
if err != nil {
t.Fatal(err)
}
return o
}
func address(t *testing.T) ShippingAddress {
t.Helper()
p, _ := NewIranianMobile("09121234567")
a, err := NewShippingAddress(AddressInput{Recipient: "Sara Ahmadi", Line1: "No. 12, Azadi St",
City: "Tehran", PostalCode: "12345-67890", Country: "ir", Phone: p})
if err != nil {
t.Fatal(err)
}
return a
}
func TestEntityEqualityIsByIdentity(t *testing.T) {
o := draftOrder(t)
sku, _ := NewSKU("SKU-42")
two, _ := NewQuantity(2)
_ = o.AddLine(sku, two, eurCents(1250))
// Same identity, different attributes: still the same order.
copyFromDB := Rehydrate(o.ID(), o.Customer(), eur, nil, ShippingAddress{}, StatusDraft, time.Time{}, 0)
if !o.SameAs(copyFromDB) {
t.Fatal("same id must be the same entity")
}
other := draftOrder(t)
if o.SameAs(other) {
t.Fatal("different ids are different orders even with equal attributes")
}
}
func TestAddLineMergesAndTotals(t *testing.T) {
o := draftOrder(t)
sku, _ := NewSKU("SKU-42")
two, _ := NewQuantity(2)
_ = o.AddLine(sku, two, eurCents(1250))
_ = o.AddLine(sku, two, eurCents(1250))
if len(o.Lines()) != 1 || o.Lines()[0].Quantity().Int() != 4 {
t.Fatalf("lines: %+v", o.Lines())
}
total, _ := o.Total()
if total != eurCents(5000) {
t.Fatalf("total %v", total)
}
lines := o.Lines()
lines[0] = OrderLine{} // mutating the copy must not touch the entity
if o.Lines()[0] == (OrderLine{}) {
t.Fatal("Lines leaked internal slice")
}
}
func TestPlaceEnforcesInvariants(t *testing.T) {
o := draftOrder(t)
if err := o.Place(time.Now()); !errors.Is(err, ErrEmptyOrder) {
t.Fatalf("want ErrEmptyOrder, got %v", err)
}
sku, _ := NewSKU("SKU-42")
one, _ := NewQuantity(1)
_ = o.AddLine(sku, one, eurCents(999))
if err := o.Place(time.Now()); !errors.Is(err, ErrInvalidAddress) {
t.Fatalf("want ErrInvalidAddress, got %v", err)
}
_ = o.ShipTo(address(t))
if err := o.Place(time.Now()); err != nil || o.Status() != StatusPlaced {
t.Fatalf("place: %v %s", err, o.Status())
}
if err := o.AddLine(sku, one, eurCents(999)); !errors.Is(err, ErrOrderNotDraft) {
t.Fatal("placed orders are closed for new lines")
}
}
func TestPriceInAnotherCurrencyIsRejected(t *testing.T) {
o := draftOrder(t)
sku, _ := NewSKU("SKU-1")
one, _ := NewQuantity(1)
irr, _ := NewMoney(5_000_000, MustCurrency("IRR"))
if err := o.AddLine(sku, one, irr); !errors.Is(err, ErrCurrencyMismatch) {
t.Fatal(err)
}
}package api
import (
"encoding/json"
"strings"
"testing"
"time"
"academy/entities-value-objects/sales"
)
func TestOrderDTOHasNoFloats(t *testing.T) {
o, _ := sales.NewOrder(sales.NewOrderID(time.Now()), sales.NewCustomerID("cus-7"), sales.MustCurrency("EUR"))
sku, _ := sales.NewSKU("SKU-42")
q, _ := sales.NewQuantity(3)
price, _ := sales.ParseMoney("0.10", sales.MustCurrency("EUR"))
_ = o.AddLine(sku, q, price)
dto, err := FromOrder(o)
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(dto)
if !strings.Contains(string(b), `"amount_minor":30`) || !strings.Contains(string(b), `"formatted":"0.30 EUR"`) {
t.Fatalf("unexpected json %s", b)
}
}The Go angle
| Go feature | Role for entities and values | Note |
|---|---|---|
Unexported fields + NewX | The only door into a value | Code in the same package can still build Money{}; keep the package small |
| Value receivers | Methods get a copy; "with-ers" are free | Use pointer receivers only on entities |
| Comparable structs | == and map keys for values | "Struct types are comparable if all their field types are comparable" (spec) |
comparable constraint | Generic sets/caches of values | Interfaces holding non-comparable types panic on == |
| Generics | A generic Money[C Currency] is possible but rarely worth it | A runtime Currency field is simpler and serialisable |
database/sql | Scanner, driver.Valuer | One column per value; multi-column values in the repository |
encoding/json | Marshaler/Unmarshaler | Prefer DTOs at the edge over marshalers on domain types |
testing fuzz, testing/quick | Property and fuzz tests | testing/quick "is frozen and is not accepting new features"; seeded math/rand/v2 loops or native fuzzing |
Laravel
Laravel 13 on PHP 8.4 (final readonly class, asymmetric visibility, typed class constants). Files live under docs/snippets/ddd/entities-value-objects/php; PHP is not installed on the authoring machine, so the code was reviewed, not run.
Before: the Eloquent model is the entity, primitives everywhere
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* BEFORE: the Eloquent model is the "entity", every attribute is a primitive
* and every caller can set anything. It works; it is bad design.
*/
class Order extends Model
{
protected $fillable = [
'status', 'total', 'currency', 'city', 'postal_code', 'phone',
];
protected $casts = [
'total' => 'float', // 0.1 + 0.2 !== 0.3
];
}
// Anywhere in the code base:
// $order->status = 'Shiped'; // typo, saved
// $order->total = $order->total * 1.09; // float rounding drift
// $order->phone = '۰۹۱۲۱۲۳۴۵۶۷'; // three spellings of one number in one column
// $order->save();Value objects
<?php
declare(strict_types=1);
namespace App\Domain\Sales;
/**
* A backed enum is a value object with a closed set of instances.
* Exponents from the ISO 4217 list one (SIX, published 2026-09-17).
*/
enum Currency: string
{
case EUR = 'EUR';
case USD = 'USD';
case IRR = 'IRR';
case JPY = 'JPY';
case KWD = 'KWD';
public function minorUnits(): int
{
return match ($this) {
self::JPY => 0,
self::KWD => 3,
self::EUR, self::USD, self::IRR => 2,
};
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
use DomainException;
/** One exception type for every broken value-object invariant. */
final class InvalidValue extends DomainException
{
/** @param list<string> $problems */
public static function because(string $type, array $problems): self
{
return new self($type.': '.implode('; ', $problems));
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
use JsonSerializable;
/**
* Money in minor units (int), never float. final + readonly: no subclass can
* add mutable state, no property can be written after construction.
*/
final readonly class Money implements JsonSerializable
{
private function __construct(
public int $minor,
public Currency $currency,
) {}
public static function ofMinor(int $minor, Currency $currency): self
{
return new self($minor, $currency);
}
/** Parse "22.50" without passing through float. */
public static function parse(string $decimal, Currency $currency): self
{
if (preg_match('/^(-?)(\d+)(?:\.(\d+))?$/', trim($decimal), $m) !== 1
|| strlen($m[3] ?? '') > $currency->minorUnits()) {
throw InvalidValue::because('Money', ["\"{$decimal}\" is not a {$currency->value} amount"]);
}
$frac = str_pad($m[3] ?? '', $currency->minorUnits(), '0');
$minor = (int) ($m[2].$frac);
return new self($m[1] === '-' ? -$minor : $minor, $currency);
}
public static function zero(Currency $currency): self
{
return new self(0, $currency);
}
/** Closed operation: Money + Money = Money. */
public function add(self $other): self
{
$this->assertSameCurrency($other);
return new self($this->minor + $other->minor, $this->currency);
}
public function subtract(self $other): self
{
$this->assertSameCurrency($other);
return new self($this->minor - $other->minor, $this->currency);
}
public function times(Quantity $quantity): self
{
return new self($this->minor * $quantity->value, $this->currency);
}
/** Half-closed: Money x Percentage -> Money, rounded half away from zero. */
public function percentOf(Percentage $p): self
{
$num = $this->minor * $p->basisPoints;
$q = intdiv($num, 10_000);
$r = $num % 10_000;
if ($r * 2 >= 10_000) {
$q++;
} elseif ($r * 2 <= -10_000) {
$q--;
}
return new self($q, $this->currency);
}
/**
* Split without losing a minor unit; the remainder goes to the first parts.
*
* @param list<int> $ratios
* @return list<self>
*/
public function allocate(array $ratios): array
{
$total = array_sum($ratios);
if ($total <= 0 || min($ratios) < 0) {
throw InvalidValue::because('Money', ['ratios must be non-negative and not all zero']);
}
$shares = [];
$remainder = $this->minor;
foreach ($ratios as $ratio) {
$share = intdiv($this->minor * $ratio, $total);
$shares[] = $share;
$remainder -= $share;
}
for ($i = 0; $remainder !== 0; $i = ($i + 1) % count($shares)) {
$step = $remainder > 0 ? 1 : -1;
$shares[$i] += $step;
$remainder -= $step;
}
return array_map(fn (int $s): self => new self($s, $this->currency), $shares);
}
public function equals(self $other): bool
{
return $this->minor === $other->minor && $this->currency === $other->currency;
}
public function isNegative(): bool
{
return $this->minor < 0;
}
public function format(): string
{
$e = $this->currency->minorUnits();
$abs = abs($this->minor);
$sign = $this->minor < 0 ? '-' : '';
if ($e === 0) {
return "{$sign}{$abs} {$this->currency->value}";
}
$p = 10 ** $e;
return sprintf('%s%d.%0'.$e.'d %s', $sign, intdiv($abs, $p), $abs % $p, $this->currency->value);
}
/** @return array{amount_minor: int, currency: string} */
public function jsonSerialize(): array
{
return ['amount_minor' => $this->minor, 'currency' => $this->currency->value];
}
private function assertSameCurrency(self $other): void
{
if ($this->currency !== $other->currency) {
throw InvalidValue::because('Money', ["cannot combine {$this->currency->value} with {$other->currency->value}"]);
}
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
final readonly class Quantity
{
public const int MAX_PER_LINE = 50;
public function __construct(public int $value)
{
if ($value < 1 || $value > self::MAX_PER_LINE) {
throw InvalidValue::because('Quantity', ["{$value} not in 1..".self::MAX_PER_LINE]);
}
}
public function add(self $other): self
{
return new self($this->value + $other->value); // constructor re-checks the cap
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
/** Percentage in basis points (1% = 100 bp), so 12.5% is exact. */
final readonly class Percentage
{
public function __construct(public int $basisPoints)
{
if ($basisPoints < 0 || $basisPoints > 10_000) {
throw InvalidValue::because('Percentage', ["{$basisPoints} bp not in 0..10000"]);
}
}
public function equals(self $other): bool
{
return $this->basisPoints === $other->basisPoints;
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
/**
* Half-open range [start, end) of calendar days, stored as UTC dates at
* midnight so equality does not depend on the caller's time zone.
*/
final readonly class DateRange
{
public DateTimeImmutable $start;
public DateTimeImmutable $end;
public function __construct(DateTimeInterface $start, DateTimeInterface $end)
{
$utc = new DateTimeZone('UTC');
$this->start = DateTimeImmutable::createFromInterface($start)->setTimezone($utc)->setTime(0, 0);
$this->end = DateTimeImmutable::createFromInterface($end)->setTimezone($utc)->setTime(0, 0);
if ($this->start >= $this->end) {
throw InvalidValue::because('DateRange', [
"start {$this->start->format('Y-m-d')} is not before end {$this->end->format('Y-m-d')}",
]);
}
}
public function contains(DateTimeInterface $t): bool
{
return $t >= $this->start && $t < $this->end;
}
public function overlaps(self $other): bool
{
return $this->start < $other->end && $other->start < $this->end;
}
public function equals(self $other): bool
{
return $this->start == $other->start && $this->end == $other->end;
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
use Illuminate\Support\Str;
/**
* Typed identity. Generated by the application (UUIDv7) so it exists before
* the INSERT and can serve as an idempotency key and an event field.
*/
final readonly class OrderId
{
private function __construct(public string $value) {}
public static function generate(): self
{
return new self((string) Str::uuid7());
}
public static function fromString(string $value): self
{
if (! Str::isUuid($value)) {
throw InvalidValue::because('OrderId', ["\"{$value}\" is not a UUID"]);
}
return new self(strtolower($value));
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
public function __toString(): string
{
return $this->value;
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
final readonly class Email
{
public string $value;
public function __construct(string $raw)
{
$raw = trim($raw);
$at = strrpos($raw, '@');
if ($at === false || filter_var($raw, FILTER_VALIDATE_EMAIL) === false) {
throw InvalidValue::because('Email', ["\"{$raw}\" is not an e-mail address"]);
}
// Lower-case the domain only; the local part may be case-sensitive.
$this->value = substr($raw, 0, $at).'@'.strtolower(substr($raw, $at + 1));
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
/**
* Iranian mobile number, stored as E.164 (+989xxxxxxxxx).
* Persian and Arabic-Indic digits are mapped explicitly: Unicode
* normalisation (NFC/NFKC) leaves them as they are.
*/
final readonly class PhoneNumber
{
private const array DIGITS = [
'۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4',
'۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9',
'٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4',
'٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9',
];
private function __construct(public string $e164) {}
public static function iranianMobile(string $raw): self
{
$d = strtr($raw, self::DIGITS);
$d = str_replace([' ', '-', '(', ')'], '', $d);
$d = preg_replace('/^\+/', '00', $d);
if (preg_match('/^\d+$/', (string) $d) !== 1) {
throw InvalidValue::because('PhoneNumber', ["\"{$raw}\" contains non-digits"]);
}
$d = match (true) {
str_starts_with($d, '0098') => substr($d, 4),
str_starts_with($d, '98') && strlen($d) === 12 => substr($d, 2),
str_starts_with($d, '0') => substr($d, 1),
default => $d,
};
if (preg_match('/^9\d{9}$/', $d) !== 1) {
throw InvalidValue::because('PhoneNumber', ["\"{$raw}\" is not an Iranian mobile number"]);
}
return new self('+98'.$d);
}
/** "0912 123 4567" */
public function national(): string
{
$n = '0'.substr($this->e164, 3);
return substr($n, 0, 4).' '.substr($n, 4, 3).' '.substr($n, 7);
}
public function equals(self $other): bool
{
return $this->e164 === $other->e164;
}
}ShippingAddress implements Laravel's Castable so a model can say 'ship_to' => ShippingAddress::class. That puts one framework interface on a domain class; if you want the domain free of Illuminate, drop Castable and write 'ship_to' => AsShippingAddress::class on the model instead.
<?php
declare(strict_types=1);
namespace App\Domain\Sales;
use Illuminate\Contracts\Database\Eloquent\Castable;
use App\Casts\AsShippingAddress;
/**
* Value object: replace it, never edit it. Collects every problem so a form
* can show them all at once.
*/
final readonly class ShippingAddress implements Castable
{
public function __construct(
public string $recipient,
public string $line1,
public string $line2,
public string $city,
public string $province,
public string $postalCode,
public string $country,
public PhoneNumber $phone,
) {
$problems = self::problems($recipient, $line1, $city, $postalCode, $country);
if ($problems !== []) {
throw InvalidValue::because('ShippingAddress', $problems);
}
}
/**
* Named constructor that normalises raw input and reports the phone
* problem together with every other problem, so a form gets all of them.
*
* @param array<string, string> $in
*/
public static function fromInput(array $in): self
{
$postal = str_replace(['-', ' '], '', $in['postal_code'] ?? '');
$country = strtoupper(trim($in['country'] ?? ''));
$problems = self::problems(trim($in['recipient'] ?? ''), trim($in['line1'] ?? ''),
trim($in['city'] ?? ''), $postal, $country);
$phone = null;
try {
$phone = PhoneNumber::iranianMobile($in['phone'] ?? '');
} catch (InvalidValue $e) {
$problems[] = 'phone: '.$e->getMessage();
}
if ($problems !== [] || $phone === null) {
throw InvalidValue::because('ShippingAddress', $problems);
}
return new self(trim($in['recipient']), trim($in['line1']), trim($in['line2'] ?? ''),
trim($in['city']), trim($in['province'] ?? ''), $postal, $country, $phone);
}
/** @return list<string> */
private static function problems(string $recipient, string $line1, string $city,
string $postalCode, string $country): array
{
$problems = [];
foreach (['recipient' => $recipient, 'line1' => $line1, 'city' => $city, 'country' => $country] as $field => $v) {
if (trim($v) === '') {
$problems[] = "{$field} is required";
}
}
if ($country === 'IR' && preg_match('/^\d{10}$/', $postalCode) !== 1) {
$problems[] = 'postal code must be 10 digits in IR';
}
return $problems;
}
/** A "with-er" in PHP 8.4: build a new instance with one field changed. */
public function withLine2(string $line2): self
{
return new self($this->recipient, $this->line1, trim($line2), $this->city,
$this->province, $this->postalCode, $this->country, $this->phone);
}
public function equals(self $other): bool
{
return $this->recipient === $other->recipient && $this->line1 === $other->line1
&& $this->line2 === $other->line2 && $this->city === $other->city
&& $this->province === $other->province && $this->postalCode === $other->postalCode
&& $this->country === $other->country && $this->phone->equals($other->phone);
}
/** @return array<string, string> */
public function toArray(): array
{
return [
'recipient' => $this->recipient, 'line1' => $this->line1, 'line2' => $this->line2,
'city' => $this->city, 'province' => $this->province,
'postal_code' => $this->postalCode, 'country' => $this->country,
'phone' => $this->phone->e164,
];
}
public static function castUsing(array $arguments): string
{
return AsShippingAddress::class;
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
/** Enum as value object: closed set, behaviour on the value. */
enum OrderStatus: string
{
case Draft = 'draft';
case Placed = 'placed';
case Paid = 'paid';
case Dispatched = 'dispatched';
case Cancelled = 'cancelled';
public function canCancel(): bool
{
return $this === self::Draft || $this === self::Placed;
}
public function acceptsLines(): bool
{
return $this === self::Draft;
}
}The entity
public private(set) (PHP 8.4 asymmetric visibility) gives public reads and private writes without getters; there are no setters:
<?php
declare(strict_types=1);
namespace App\Domain\Sales;
/** Value object inside the Order: identified by its SKU within its order. */
final readonly class OrderLine
{
public function __construct(
public string $sku,
public Quantity $quantity,
public Money $unitPrice,
) {
if ($sku === '' || $unitPrice->isNegative()) {
throw InvalidValue::because('OrderLine', ['sku required and unit price must be >= 0']);
}
}
public function total(): Money
{
return $this->unitPrice->times($this->quantity);
}
public function withQuantity(Quantity $quantity): self
{
return new self($this->sku, $quantity, $this->unitPrice);
}
}<?php
declare(strict_types=1);
namespace App\Domain\Sales;
use DateTimeImmutable;
use DomainException;
/**
* Entity: identity (OrderId) + lifecycle. No public setters; state changes
* only through intention-revealing methods that guard the invariants.
* PHP 8.4 asymmetric visibility makes reads public and writes private.
*/
final class Order
{
/** @var list<OrderLine> */
public private(set) array $lines = [];
public private(set) OrderStatus $status = OrderStatus::Draft;
public private(set) ?ShippingAddress $shipTo = null;
public private(set) ?DateTimeImmutable $placedAt = null;
public function __construct(
public readonly OrderId $id,
public readonly string $customerId,
public readonly Currency $currency,
) {}
public function addLine(string $sku, Quantity $quantity, Money $unitPrice): void
{
if (! $this->status->acceptsLines()) {
throw new DomainException("Order {$this->id} is {$this->status->value}; lines are closed.");
}
if ($unitPrice->currency !== $this->currency) {
throw new DomainException("Order {$this->id} is in {$this->currency->value}.");
}
foreach ($this->lines as $i => $line) {
if ($line->sku === $sku) {
$this->lines[$i] = $line->withQuantity($line->quantity->add($quantity));
return;
}
}
$this->lines[] = new OrderLine($sku, $quantity, $unitPrice);
}
public function shipTo(ShippingAddress $address): void
{
if (! in_array($this->status, [OrderStatus::Draft, OrderStatus::Placed], true)) {
throw new DomainException("Cannot change the address of a {$this->status->value} order.");
}
$this->shipTo = $address; // replace the whole value
}
public function total(): Money
{
return array_reduce(
$this->lines,
fn (Money $sum, OrderLine $l): Money => $sum->add($l->total()),
Money::zero($this->currency),
);
}
public function place(DateTimeImmutable $now): void
{
if ($this->status !== OrderStatus::Draft) {
throw new DomainException("Order {$this->id} is already {$this->status->value}.");
}
if ($this->lines === [] || $this->shipTo === null) {
throw new DomainException("Order {$this->id} needs lines and a shipping address.");
}
$this->status = OrderStatus::Placed;
$this->placedAt = $now;
}
/** Entity equality: same identity, whatever the attributes. */
public function sameAs(self $other): bool
{
return $this->id->equals($other->id);
}
/**
* Rebuild from storage. Bypasses creation rules on purpose; only the
* repository calls it.
*
* @param list<OrderLine> $lines
*/
public static function rehydrate(OrderId $id, string $customerId, Currency $currency, array $lines,
OrderStatus $status, ?ShippingAddress $shipTo, ?DateTimeImmutable $placedAt): self
{
$order = new self($id, $customerId, $currency);
$order->lines = $lines;
$order->status = $status;
$order->shipTo = $shipTo;
$order->placedAt = $placedAt;
return $order;
}
}Persistence: casts, record models and a repository
AsMoney is an embedded value over two columns (cast parameters are "passed to the constructor"); AsShippingAddress serialises to one JSON column; enum casts handle Currency and OrderStatus:
<?php
declare(strict_types=1);
namespace App\Casts;
use App\Domain\Sales\Currency;
use App\Domain\Sales\Money;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
/**
* Embedded value: one Money attribute <-> two columns, {prefix}_minor and
* {prefix}_currency. Usage in casts(): 'total' => AsMoney::class.':total'
*
* @implements CastsAttributes<Money, Money>
*/
final class AsMoney implements CastsAttributes
{
public function __construct(private string $prefix) {}
public function get(Model $model, string $key, mixed $value, array $attributes): ?Money
{
$minor = $attributes["{$this->prefix}_minor"] ?? null;
$currency = $attributes["{$this->prefix}_currency"] ?? null;
if ($minor === null || $currency === null) {
return null;
}
return Money::ofMinor((int) $minor, Currency::from($currency));
}
/** @return array<string, int|string> */
public function set(Model $model, string $key, mixed $value, array $attributes): array
{
if (! $value instanceof Money) {
throw new InvalidArgumentException("{$key} must be a Money instance.");
}
return [
"{$this->prefix}_minor" => $value->minor,
"{$this->prefix}_currency" => $value->currency->value,
];
}
}<?php
declare(strict_types=1);
namespace App\Casts;
use App\Domain\Sales\ShippingAddress;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
/**
* Serialized value: ShippingAddress <-> one JSON column. Reached through
* ShippingAddress::castUsing(), so the model says 'ship_to' => ShippingAddress::class.
*
* @implements CastsAttributes<ShippingAddress, ShippingAddress>
*/
final class AsShippingAddress implements CastsAttributes
{
/** The value is immutable, so caching the instance is safe but pointless. */
public bool $withoutObjectCaching = true;
public function get(Model $model, string $key, mixed $value, array $attributes): ?ShippingAddress
{
if ($value === null) {
return null;
}
// Re-validates on read: a bad legacy row fails loudly here, not in a template.
return ShippingAddress::fromInput(json_decode($value, true, flags: JSON_THROW_ON_ERROR));
}
/** @return array<string, string|null> */
public function set(Model $model, string $key, mixed $value, array $attributes): array
{
if ($value !== null && ! $value instanceof ShippingAddress) {
throw new InvalidArgumentException("{$key} must be a ShippingAddress.");
}
return [$key => $value === null ? null : json_encode($value->toArray(), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)];
}
}<?php
declare(strict_types=1);
namespace App\Models;
use App\Casts\AsMoney;
use App\Domain\Sales\Currency;
use App\Domain\Sales\OrderStatus;
use App\Domain\Sales\ShippingAddress;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Persistence model for the orders table. It is NOT the domain entity:
* EloquentOrderRepository maps between this record and App\Domain\Sales\Order.
*/
final class OrderRecord extends Model
{
protected $table = 'orders';
public $incrementing = false; // the id comes from OrderId::generate()
protected $keyType = 'string';
public $timestamps = false; // the orders table has no created_at/updated_at
protected $guarded = [];
protected function casts(): array
{
return [
'currency' => Currency::class, // enum cast
'status' => OrderStatus::class, // enum cast
'ship_to' => ShippingAddress::class, // Castable -> AsShippingAddress (JSON)
'total' => AsMoney::class.':total', // two columns: total_minor, total_currency
'placed_at' => 'immutable_datetime',
];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLineRecord::class, 'order_id');
}
}<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/** Rows of the dependent order_lines table: (order_id, sku) is the key. */
final class OrderLineRecord extends Model
{
protected $table = 'order_lines';
public $incrementing = false;
public $timestamps = false;
protected $guarded = [];
}<?php
declare(strict_types=1);
namespace App\Infrastructure;
use App\Domain\Sales\Money;
use App\Domain\Sales\Order;
use App\Domain\Sales\OrderId;
use App\Domain\Sales\OrderLine;
use App\Domain\Sales\Quantity;
use App\Models\OrderLineRecord;
use App\Models\OrderRecord;
use Illuminate\Support\Facades\DB;
/** The only class that knows both the entity and the tables. */
final class EloquentOrderRepository
{
public function save(Order $order): void
{
DB::transaction(function () use ($order): void {
OrderRecord::query()->updateOrCreate(['id' => $order->id->value], [
'customer_id' => $order->customerId,
'currency' => $order->currency,
'status' => $order->status,
'ship_to' => $order->shipTo,
'total' => $order->total(),
'placed_at' => $order->placedAt,
]);
// Lines are values: replace the whole collection.
OrderLineRecord::query()->where('order_id', $order->id->value)->delete();
OrderLineRecord::query()->insert(array_map(fn (OrderLine $l): array => [
'order_id' => $order->id->value,
'sku' => $l->sku,
'quantity' => $l->quantity->value,
'unit_price_minor' => $l->unitPrice->minor,
], $order->lines));
});
}
public function find(OrderId $id): ?Order
{
$record = OrderRecord::query()->with('lines')->find($id->value);
if ($record === null) {
return null;
}
$lines = $record->lines
->sortBy('sku')
->map(fn (OrderLineRecord $l): OrderLine => new OrderLine(
$l->sku,
new Quantity((int) $l->quantity),
Money::ofMinor((int) $l->unit_price_minor, $record->currency),
))
->values()
->all();
return Order::rehydrate($id, $record->customer_id, $record->currency, $lines,
$record->status, $record->ship_to, $record->placed_at);
}
}The API edge
<?php
declare(strict_types=1);
namespace App\Http\Resources;
use App\Domain\Sales\Money;
use App\Domain\Sales\Order;
use App\Domain\Sales\OrderLine;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* The API contract. Value objects are mapped to explicit fields; renaming a
* property inside Money must not change the JSON clients see.
*
* @property Order $resource
*/
final class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
$money = fn (Money $m): array => [
'amount_minor' => $m->minor,
'currency' => $m->currency->value,
'formatted' => $m->format(),
];
return [
'id' => $this->resource->id->value,
'status' => $this->resource->status->value,
'lines' => array_map(fn (OrderLine $l): array => [
'sku' => $l->sku,
'quantity' => $l->quantity->value,
'unit_price' => $money($l->unitPrice),
], $this->resource->lines),
'total' => $money($this->resource->total()),
'placed_at' => $this->resource->placedAt?->format(DATE_ATOM),
];
}
}Tests
<?php
declare(strict_types=1);
namespace Tests\Unit\Sales;
use App\Domain\Sales\Currency;
use App\Domain\Sales\InvalidValue;
use App\Domain\Sales\Money;
use App\Domain\Sales\PhoneNumber;
use App\Domain\Sales\Quantity;
use Error;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
final class MoneyTest extends TestCase
{
public function test_equality_is_by_value_not_by_instance(): void
{
$a = Money::parse('22.50', Currency::EUR);
$b = Money::ofMinor(2250, Currency::EUR);
$this->assertTrue($a->equals($b));
$this->assertFalse($a === $b); // different instances, same value
$this->assertTrue($a == $b); // PHP ==: same class, equal properties
}
public function test_it_cannot_be_modified(): void
{
$m = Money::ofMinor(100, Currency::EUR);
$this->expectException(Error::class); // Cannot modify readonly property
$m->minor = 1; // @phpstan-ignore-line
}
public function test_add_is_closed_and_currency_safe(): void
{
$sum = Money::parse('0.10', Currency::EUR)->add(Money::parse('0.20', Currency::EUR));
$this->assertTrue($sum->equals(Money::parse('0.30', Currency::EUR)));
$this->expectException(InvalidValue::class);
$sum->add(Money::ofMinor(1, Currency::USD));
}
public function test_format_uses_iso_exponent(): void
{
$this->assertSame('1500 JPY', Money::ofMinor(1500, Currency::JPY)->format());
$this->assertSame('1.234 KWD', Money::ofMinor(1234, Currency::KWD)->format());
$this->assertSame('-0.05 EUR', Money::ofMinor(-5, Currency::EUR)->format());
}
/** Property-style test: 1,000 random cases, fixed seed for reproducibility. */
public function test_allocate_never_loses_a_minor_unit(): void
{
mt_srand(42);
for ($i = 0; $i < 1000; $i++) {
$amount = mt_rand(-1_000_000, 1_000_000);
$ratios = array_map(fn () => mt_rand(1, 5), range(1, mt_rand(1, 6)));
$parts = Money::ofMinor($amount, Currency::EUR)->allocate($ratios);
$sum = array_reduce($parts, fn (Money $s, Money $p) => $s->add($p), Money::zero(Currency::EUR));
$this->assertSame($amount, $sum->minor, 'ratios '.implode(',', $ratios));
}
}
public function test_quantity_invariant_survives_addition(): void
{
$this->expectException(InvalidValue::class);
(new Quantity(30))->add(new Quantity(30));
}
#[DataProvider('iranianMobiles')]
public function test_iranian_mobile_spellings_normalise_to_one_value(string $raw): void
{
$this->assertSame('+989121234567', PhoneNumber::iranianMobile($raw)->e164);
}
public static function iranianMobiles(): array
{
return [['09121234567'], ['+98 912 123 4567'], ['0098-912-123-4567'], ['۰۹۱۲۱۲۳۴۵۶۷'], ['٠٩١٢١٢٣٤٥٦٧']];
}
}<?php
declare(strict_types=1);
namespace Tests\Unit\Sales;
use App\Domain\Sales\Currency;
use App\Domain\Sales\DateRange;
use App\Domain\Sales\InvalidValue;
use App\Domain\Sales\Money;
use App\Domain\Sales\Order;
use App\Domain\Sales\OrderId;
use App\Domain\Sales\OrderStatus;
use App\Domain\Sales\Percentage;
use App\Domain\Sales\Quantity;
use App\Domain\Sales\ShippingAddress;
use DateTimeImmutable;
use DomainException;
use PHPUnit\Framework\TestCase;
final class OrderTest extends TestCase
{
private function address(): ShippingAddress
{
return ShippingAddress::fromInput([
'recipient' => 'Sara Ahmadi', 'line1' => 'No. 12, Azadi St', 'city' => 'Tehran',
'postal_code' => '12345-67890', 'country' => 'ir', 'phone' => '09121234567',
]);
}
public function test_entity_equality_is_by_identity(): void
{
$id = OrderId::fromString('0190f3c2-7b1e-7a00-8000-000000000001');
$a = new Order($id, 'cus-7', Currency::EUR);
$a->addLine('SKU-42', new Quantity(2), Money::ofMinor(1250, Currency::EUR));
$b = Order::rehydrate($id, 'cus-7', Currency::EUR, [], OrderStatus::Draft, null, null);
$c = new Order(OrderId::fromString('0190f3c2-7b1e-7a00-8000-000000000002'), 'cus-7', Currency::EUR);
$this->assertTrue($a->sameAs($b)); // same id, different lines
$this->assertFalse($b->sameAs($c)); // equal attributes, different id
}
public function test_add_line_merges_by_sku_and_totals(): void
{
$o = new Order(OrderId::generate(), 'cus-7', Currency::EUR);
$o->addLine('SKU-42', new Quantity(2), Money::ofMinor(1250, Currency::EUR));
$o->addLine('SKU-42', new Quantity(2), Money::ofMinor(1250, Currency::EUR));
$this->assertCount(1, $o->lines);
$this->assertSame(4, $o->lines[0]->quantity->value);
$this->assertTrue($o->total()->equals(Money::ofMinor(5000, Currency::EUR)));
}
public function test_place_enforces_invariants_and_closes_the_order(): void
{
$o = new Order(OrderId::generate(), 'cus-7', Currency::EUR);
try {
$o->place(new DateTimeImmutable());
$this->fail('an empty order must not be placed');
} catch (DomainException) {
}
$o->addLine('SKU-1', new Quantity(1), Money::ofMinor(999, Currency::EUR));
$o->shipTo($this->address());
$o->place(new DateTimeImmutable());
$this->assertSame(OrderStatus::Placed, $o->status);
$this->expectException(DomainException::class);
$o->addLine('SKU-1', new Quantity(1), Money::ofMinor(999, Currency::EUR));
}
public function test_address_reports_every_problem_at_once(): void
{
try {
ShippingAddress::fromInput(['country' => 'IR', 'postal_code' => '123', 'phone' => 'x']);
$this->fail('invalid address accepted');
} catch (InvalidValue $e) {
foreach (['phone', 'recipient', 'line1', 'city', 'postal code'] as $word) {
$this->assertStringContainsString($word, $e->getMessage());
}
}
}
public function test_percent_and_date_range(): void
{
$vat = Money::ofMinor(1250, Currency::EUR)->percentOf(new Percentage(900));
$this->assertSame(113, $vat->minor); // 112.5 rounds half away from zero
$this->expectException(InvalidValue::class); // same day = empty day range
new DateRange(new DateTimeImmutable('2026-03-21 09:00'), new DateTimeImmutable('2026-03-21 17:00'));
}
}The Laravel angle
| Laravel feature | Role | Caveat |
|---|---|---|
CastsAttributes (get/set) | Map a value to one or many columns | Docs: "any changes made to the value object will automatically be synced back to the model" assumes mutable values; with readonly values, assign a new instance |
Castable::castUsing | The value names its own caster | Framework interface on a domain class |
withoutObjectCaching | Disable Eloquent's per-attribute instance cache | Harmless for immutable values |
CastsInboundAttributes | Transform on write only (hashing) | Not a value object |
SerializesCastableAttributes | Control toArray/toJson of the cast value | Prefer an explicit JsonResource for APIs |
ComparesCastableAttributes | Decide when a cast value is "dirty" | Use equals() for value comparison |
Enum casts, AsEnumCollection | Backed enums as attributes | Unknown values throw ValueError |
Attribute::make(get:, set:) | Accessor building a value from several columns ($attributes) | Fine for read models |
HasUuids, Str::uuid7() | Application-generated UUIDv7 ids | Set $incrementing = false, $keyType = 'string' |
$model->is($other) | Entity equality for Eloquent models | Compares key, table and connection |
JsonResource | DTO at the edge | The contract; do not return models directly |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Mutable value objects | Make them immutable | Unexported fields / readonly; with-ers | No aliasing bugs | More allocations (negligible for small values) |
| Entities with public setters | Intention-revealing methods | Place(), ShipTo() instead of setStatus() | Invariants in one place | Mapping code for persistence |
| Value objects with ids | Remove the id; key by owner + attributes | Dependent table (order_id, sku) | Honest model, simpler equality | ORM may want a surrogate key; keep it out of the domain |
| Eloquent model used as the entity everywhere | Separate record from entity where logic is rich | Repository maps OrderRecord to Order | Domain testable without DB | Two classes per concept |
| Floats for money | Integer minor units | Money{minor int64, currency} | Exact sums | Formatting and parsing code |
| Primitive obsession | Introduce whole values gradually | PhoneNumber, Email, OrderId | Type checking, one validation point | More small types |
Mutable value objects
Symptom: a method like Money::setAmount() or $address->city = .... Fix: remove the setter, add withX() returning a new instance, and replace the value on the entity through a method that checks lifecycle rules (Order::shipTo). In Go, change pointer receivers on value types to value receivers.
Entities with public setters
Symptom: order.SetStatus("dispatched") callable from anywhere, so the rule "only paid orders are dispatched" lives in controllers. Fix: one method per business operation (MarkDispatched), unexported/private(set) state, and a Rehydrate path for the repository only. See Anemic vs Rich Domain Models.
Value objects with ids
Symptom: order_lines.id exists and code compares lines by it, or another table points to a line id. Fix: if nothing outside the order refers to a line, drop the id from the model (the table may keep a surrogate for the ORM) and identify lines by (order_id, sku). If something does refer to it, it is a local entity: model that honestly.
Eloquent models as entities, and when that is acceptable
Using the Eloquent model as the entity is fine when the domain is CRUD-like (a Supporting or Generic subdomain, Domains & Subdomains): admin back-offices, settings, catalogue editing. Even then, put value objects on the model with casts ('total' => AsMoney::class.':total', enum casts). Split record and entity when the Core domain has rules that must be tested without a database, when several entry points (HTTP, queue, import) must share invariants, or when the model must not expose save(), fill() and mass assignment to callers.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Anything with currency | Money value, integer minor units | Allocate, explicit rounding | Floats lose cents; currencies must not mix |
| Thing followed through states | Entity with typed id | Rehydrate, version column | Identity and lifecycle |
| Id format, single database | UUIDv7 or bigint identity | Typed OrderId | Ordered inserts; generated before persistence with UUIDv7 |
| Id visible to customers | Separate display number | Value object OrderNumber | Change formatting without touching keys |
| Contact data | Email, PhoneNumber | Canonical form at construction | Dedup, equality, carrier APIs |
| Collection of small parts | Values in a dependent table | Replace-the-set on save | No fake ids in the model |
| Snapshot of another context's data | Value (e.g. bill-to address at invoicing) | JSON column | It must not change when the source changes |
| Closed set of states | Enum value | Methods for rules | Parsing and rules in one place |
| CRUD-heavy supporting context | Eloquent model as entity | Casts for values | Less mapping code where rules are thin |
| Core domain with rich rules | Separate domain entity + record model | Repository mapping | Testable, framework-free rules |
In architecture: from a single process to a distributed system
The same Order and its values at each stage. Values travel well; identities must be globally unique once data leaves one database.
Monolith: one process, one database
How it shows up: value objects live in the Sales module and are imported freely within it; Order is saved in one transaction with its lines.
Example (simple): a single Laravel app: OrderRecord with AsMoney and enum casts, OrderStatus enum, controllers using OrderResource. No separate domain entity yet; the values already remove float and typo bugs.
Example (production-shaped): the same app after six months: checkout rules grew, so App\Domain\Sales\Order was introduced with EloquentOrderRepository; the OrderRecord is now used only by the repository and the admin panel.
Modular monolith and multiple databases
How it shows up: each module owns its values. Sharing a Money package across Sales and Billing is a deliberate shared kernel (Context Maps); sharing Order is not. Cross-module references are ids (OrderId as a string at the module boundary).
Modular monolith, one deployable, two schemas
1 Sales: BEGIN (sales schema) -> INSERT orders, order_lines, outbox(OrderPlacedV1) -> COMMIT
2 In-process relay dispatches OrderPlacedV1 to Billing's handler
3 Billing: decodes DTO -> billing.Money (its own type or the shared kernel) -> Invoice entity
4 Billing stores order_id as a plain uuid column: no FK into sales.ordersMicroservices: values become contracts
What survives: the rules of a value (minor units, ISO codes, E.164) as a documented published language; ids as strings; immutability of events. What does not: the type itself. Each service has its own Money implementation; a shared library of domain values across services couples deployments (Service Boundaries).
sales-svc -> billing-svc, fulfilment-svc
1 POST /orders Idempotency-Key -> sales-svc: NewOrderID (UUIDv7) before any DB call
2 sales-svc commits order + outbox; relay publishes sales.order.placed.v1
3 billing-svc: amount_minor + currency -> its Money; invoice keyed by order_id
4 fulfilment-svc: lines -> ShipmentItem entities with their own ids
5 Duplicate delivery: consumers dedup on event_id; order_id is stable because the client-side retry reused itDistributed data: replicas, caches and multi-region
| Where values and ids meet distribution | What breaks | Design response |
|---|---|---|
| Ids generated in many nodes/regions | Collisions, hot index pages | UUIDv7/ULID or Snowflake (ID Generation) |
| Cached serialised values (Redis) | Old shape after a deploy; float formatting | Version the cache key; DTO shape, not serialize() of objects |
| Read replicas | Stale entity version | version column, read-your-writes for the owner |
| Times across regions | == on time.Time, DST surprises | Store UTC instants; zone only at display (Asia/Tehran) |
| Money across currencies in reports | Summing EUR with IRR | Group by currency; convert with a dated rate as its own value |
| Text keys from many clients | Persian vs Arabic letters and digits | Canonicalise in the value constructor before storing or indexing |
Scaling path: 1×, 10×, 100×
| Scale | Entities and values | Practices |
|---|---|---|
| 1× (one team) | Values on Eloquent models via casts; Order may be the model | Money in minor units, enums, typed ids |
| 10× (several teams, modules) | Domain entities separate from records in Core modules; value packages per module; small shared kernel | Property tests for values, contract tests for DTOs, UUIDv7 ids |
| 100× (many services) | Each service owns its value types; published language for values in events | Schema registry or JSON Schema for event shapes, id generation without coordination, canonicalisation rules documented per field |
Lab: build, break and persist values
Everything runs offline with Go installed (Go 1.24 or later).
Setup.
cd docs/snippets/ddd/entities-value-objects/go
gofmt -l . && go vet ./... && go test ./...
# ok academy/entities-value-objects/api
# ? academy/entities-value-objects/before [no test files]
# ok academy/entities-value-objects/sales
# ? academy/entities-value-objects/store [no test files]Experiment 1: float drift vs minor units. Write a scratch main.go in a temporary directory:
a, b := 0.1, 0.2
fmt.Println(a+b == 0.3, a+b) // false 0.30000000000000004
fmt.Println(0.1+0.2 == 0.3) // true: untyped constants are exact, variables are notThen run go test ./sales -run TestParseMoneyNeverUsesFloat -v and see 0.30 parsed to 30 minor units.
Experiment 2: comparability. Add a slice field to a struct and compare two values: the compiler says invalid operation: a == b (struct containing []string cannot be compared). Put the same struct into a map[any]int: it compiles and panics with hash of unhashable type. This is why Order (which has a slice) is not compared with == and Money is.
Experiment 3: the allocation property. Break Allocate by deleting the remainder loop and run go test ./sales -run Allocate -v. The property test reports the first amount and ratios whose parts do not add up, and the fixed seed makes the failure reproducible.
Experiment 4: fuzz the phone parser.
go test ./sales -run XXX -fuzz FuzzIranianMobile -fuzztime 10s
# fuzz: elapsed: ..., execs: ..., new interesting: ...
# PASSNow remove the Persian-digit branch in phone.go: TestIranianMobileAcceptsEveryCommonSpelling fails on "۰۹۱۲۱۲۳۴۵۶۷".
Experiment 5: identity vs value. In order_test.go, TestEntityEqualityIsByIdentity builds a second *Order with the same id and different lines (SameAs is true) and a new order with equal attributes (SameAs is false). Change SameAs to compare totals and watch which test fails.
Experiment 6 (PostgreSQL). Load store/schema.sql into a scratch database, insert a row with quantity = 0 into order_lines and read the CHECK violation (SQLSTATE 23514, check_violation); insert currency = 'eur' and see the domain's check reject it. The database is the last line of defence, the value object the first.
Common misconceptions
| Belief | Reality |
|---|---|
| Entity = table, value object = column | DDD terms are about identity and equality; storage is a separate choice |
| Value objects are DTOs | Old J2EE usage; DDD values have behaviour and invariants, DTOs do not |
| Things that change are entities | The holder changes by replacing values; continuity of identity decides |
| Every entity needs an auto-increment id | Ids can come from the user, the app (UUIDv7), the DB or another context |
readonly makes a PHP value fully immutable | Objects inside readonly properties can still be mutated ("interior mutability") |
| Go structs are immutable because they are copied | Exported fields and pointer receivers allow mutation; slices inside share arrays |
| Floats are fine if you round at the end | Errors accumulate before rounding; use integer minor units |
| Unicode normalisation makes Persian text comparable | NFC/NFKC keep Arabic vs Farsi Yeh and Persian digits distinct; fold explicitly |
| Validation in the controller is enough | Queues, imports and tests skip controllers; invariants belong in constructors |
| Values should be serialised directly to the API | Map to DTOs; the JSON shape is a contract |
| Using Eloquent models as entities is always wrong | It is fine for CRUD-heavy supporting contexts; add value casts |
| Order lines must be entities because they have a table | Lines identified by SKU within an order are values; a table is a storage detail |
Cheat sheet
| Topic | Remember |
|---|---|
| Entity | Identity through time; equality by id; lifecycle; no public setters |
| Value object | Attributes only; immutable; equal by value; replace, do not edit |
| The question | "Would the business care if I swapped it for an identical one?" |
| Ids | Typed (OrderId); stable; generated before persistence when possible (UUIDv7) |
| Invariants | In constructors; always-valid; collect errors for forms |
| Immutability | Go: unexported fields + value receivers; PHP: final readonly class + with-ers |
| Closure | Money + Money = Money; allocate, never divide |
| Money | Integer minor units + ISO 4217 currency; exponent per currency |
| Equality | Canonical form at construction; beware floats, time.Time, Persian digits |
| Enums | PHP backed enums with methods; Go typed constants from 1 with String() |
| Persistence | Embedded columns, JSON column, dependent table, single column; re-validate on read |
| Edge | DTOs and versioned events; ids as strings, amounts as integers |
| Tests | Equality, invariants, property tests for arithmetic, fuzz for parsers |
| Eloquent | Casts for values; separate entity only where rules are rich |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What single question decides entity vs value, and who answers it? Must-know
Answer
Answer: "Would the business care if this instance were swapped for another with identical attributes?" The domain expert answers it, per bounded context. See The identity question.
2 — Quote Evans on what an entity's model must define. Good to know
Answer
Answer: "The model must define what it means to be the same thing." See Entity.
3 — Why is an application-generated UUIDv7 often better than an auto-increment id for an Order? Important
Answer
Answer: It exists before the INSERT, so it can go into the outbox event and act as a retry-stable key in the same transaction; it is time-ordered so B-tree inserts stay local; it does not leak order volume. Cost: 16 bytes and it reveals creation time. See Choosing and generating identity.
4 — Name the PHP 8.4 and Go techniques that make a value immutable. Important
Answer
Answer: PHP: final readonly class, private constructor with named constructors, with-ers returning new self(...) (or clone($this, [...]) in 8.5). Go: unexported fields, NewX constructors, value receivers returning new values, defensive copies of slices. See Immutability.
5 — Why does Money have Allocate but no Divide? Important
Answer
Answer: Division is not closed over money (10.00 / 3 is not a money amount) and silently loses minor units; allocation returns parts whose sum equals the whole. See Closure of operations.
6 — Give two reasons a Go value object containing time.Time may compare unequal for the same instant. Good to know
Answer
Answer: == compares the Location and the monotonic clock reading as well as the instant. Store UTC or civil-date fields, or compare with Equal. See Equality pitfalls.
7 — Does Unicode NFKC make "۰۹۱۲" equal to "0912"? Good to know
Answer
Answer: No. Persian digits (U+06F0..U+06F9) are unchanged by NFC and NFKC; map them explicitly in the value constructor, as PhoneNumber does. See Equality pitfalls.
8 — When is OrderLine a value and when an entity? Must-know
Answer
Answer: A value when it is identified by SKU within its order, replaced as a whole and has no own lifecycle (Sales). A local entity when it is tracked individually through picking, backorders and returns (Fulfilment's ShipmentItem). See the OrderLine debate.
9 — Name the four persistence options for value objects and one weakness of each. Important
Answer
Answer: Embedded columns (many columns for big values), JSON column (weak constraints, old shapes), dependent table (replace = delete + insert), single column (only for one-field values). See Persistence mapping.
10 — Why should an API not return the domain Money object's internal serialisation? Important
Answer
Answer: The JSON shape is a contract; renaming a private field would break clients, and other languages cannot run your constructor. Map to a DTO with amount_minor, currency and optionally formatted. See Values at the edge.
11 — When is it acceptable to use an Eloquent model as the entity? Important
Answer
Answer: In CRUD-heavy supporting or generic contexts with thin rules; still put value objects on it with casts. Split when Core rules must be tested without a database or shared by several entry points. See Eloquent as entity.
Glossary
| Term | Meaning |
|---|---|
| Entity | Object defined by a thread of identity that runs through time; equality by id (Evans) |
| Reference object | Fowler's general term for objects compared by identity; entities are one form |
| Value object | Object that matters only as the combination of its attributes; immutable, equal by value |
| Identity | What makes an entity "the same one" across changes |
| Lifecycle | The states an entity passes through (draft, placed, paid, dispatched) |
| Natural key | An identifier from the domain (ISBN, IBAN) |
| Surrogate key / surrogate identity | An identifier made by and for the system, often kept beside the domain id |
| Typed id | A value type wrapping an identifier (OrderId) so ids of different kinds cannot be mixed |
| UUIDv7 | RFC 9562 UUID with a 48-bit Unix-millisecond prefix; time-ordered |
| ULID | 128-bit lexicographically sortable id with a time prefix (see ID Generation) |
| Invariant | A rule that must always hold for an object |
| Always-valid / self-validating | An object that cannot be constructed in an invalid state |
| Fail fast | Reject at the first broken rule |
| Notification pattern | Collect all validation problems and report them together (Fowler) |
| Immutability | No operation changes observable state after construction |
| Aliasing bug | A change through one reference unexpectedly visible through another |
| With-er | Method returning a copy with one attribute changed (withLine2) |
| Side-effect-free function | Operation that returns a result without changing observable state (Evans) |
| Command-query separation | Commands change state and return no domain data; queries only return |
| Closure of operations | Operation whose argument and return types equal the implementer's type (Evans) |
| Allocation | Splitting money by ratios so the parts sum exactly to the whole |
| Minor unit | The smallest currency unit (cent); ISO 4217 gives the exponent per currency |
| ISO 4217 | Standard list of currency codes and minor-unit exponents |
| Basis point | One hundredth of a percent; 12.5% = 1250 bp |
| Whole value | A type representing one complete domain quantity rather than bare primitives (Cunningham) |
| Primitive obsession | Using strings and numbers where a domain type belongs |
| Conceptual contours | Cutting types and operations along the domain's natural divisions (Evans) |
| Conceptual whole | Attributes that only make sense together (Vernon) |
| Standard type | A widely shared value such as a currency or country code (Vernon) |
| Canonical form | The single normalised representation a value stores and compares |
| E.164 | International phone-number format, e.g. +989121234567 |
| Unicode normalisation (NFC, NFKC) | Forms that give equivalent strings one binary representation (UAX 15) |
| Monotonic clock reading | Part of Go's time.Time used for measuring durations; affects == |
| Backed enum | PHP enum whose cases have scalar values; from / tryFrom |
| Comparable (Go) | Types usable with == and as map keys |
| Embedded Value | Mapping a value's fields to columns of the owner's table (Fowler) |
| Serialized LOB | Storing an object graph in one column, e.g. JSON (Fowler) |
| Dependent Mapping | Owner's mapper also maps its child objects (Fowler) |
| Rehydration | Rebuilding an entity from storage without replaying creation rules |
CastsAttributes | Laravel interface with get/set mapping attributes to values |
Castable / castUsing | Laravel interface letting a value name its caster |
sql.Scanner / driver.Valuer | Go interfaces for reading a column into a type and writing it back |
| DTO | Data transfer object: a shape for crossing a boundary, no behaviour |
| Published language | Documented shared format used between contexts |
| Integration event | Event published to other contexts in the published language |
| Property-based test | A test that checks a rule over many generated inputs |
| Fuzzing | Coverage-guided automated input generation to find failures (Go native fuzzing) |
| Asymmetric visibility | PHP 8.4 public private(set): different read and write scopes |
| Property hooks | PHP 8.4 get/set hooks on properties; incompatible with readonly |
CREATE DOMAIN | PostgreSQL data type with constraints |
| Anemic domain model | Objects with data but no behaviour (see the sibling chapter) |
References
- Eric Evans, Domain-Driven Design Reference, 2015: Entities, Value Objects, Domain Events, Side-Effect-Free Functions, Assertions, Closure of Operations, Conceptual Contours
- Martin Fowler, "Value Object", 14 November 2016; "Evans Classification", 14 December 2005; "Anemic Domain Model"
- Martin Fowler, PoEAA catalogue: Money, Embedded Value, Serialized LOB, Dependent Mapping
- Martin Fowler, "Replacing Throwing Exceptions with Notification in Validations", 9 December 2014
- Vaughn Vernon, Implementing Domain-Driven Design (Addison-Wesley, 2013), publisher's free sample: contents, chapter summaries, chapter 10
- RFC 9562, Universally Unique IDentifiers (UUIDs), section 5.7 UUID Version 7
- ISO 4217 list one, SIX, published 2026-09-17
- Unicode Standard Annex #15, Unicode Normalization Forms
- Google libphonenumber, PhoneNumberMetadata.xml (territory IR)
- PHP manual: Readonly classes, Properties (readonly), Asymmetric visibility, Property hooks, Backed enumerations, Enumeration methods, Comparing objects, Floating point numbers; PHP 8.4 release, PHP 8.5 release; php-src
Zend/zend_enum.c - Laravel 13: Eloquent: Mutators & Casting, Eloquent (UUID keys, comparing models), API Resources, Strings, Release notes
- Go: The Go Programming Language Specification (comparison operators), Go Fuzzing, All your comparable types; package docs via
go docfordatabase/sql.Scanner,database/sql/driver.Valuer,encoding/json.Marshaler,time.Time,testing/quick(source: database/sql, time) - PostgreSQL, CREATE DOMAIN, Error codes (23514
check_violation) - RFC 5321, Simple Mail Transfer Protocol ("The local-part of a mailbox MUST BE treated as case sensitive")
- Wikipedia, Postal codes in Iran (secondary source for the 10-digit format)