Skip to content

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 (۲۰۱۵)، بخش "Value Objects"

خلاصه (Summary): موجودیت (Entity) چیزی است که هویتش در طول زمان ثابت می‌ماند در حالی که ویژگی‌هایش عوض می‌شوند؛ شیء مقداری (Value Object) چیزی است که ویژگی‌هایش آن را کامل توصیف می‌کنند، تغییرناپذیر است، با مقدار مقایسه می‌شود و به‌جای ویرایش، جایگزین می‌شود. بخش بزرگ یک مدل خوب از Value Objectها ساخته شده؛ Entityها همان چند چیزی‌اند که باید در طول زمان دنبالشان کنید. تمرکز (Focus): پرسش هویت («برایمان مهم است کدام‌یکی است؟»)، انتخاب و تولید شناسه (طبیعی در برابر جانشین، UUIDv7، شناسهٔ تایپ‌دار OrderId)، Value Objectهای همیشه‌معتبر با invariant در سازنده، تغییرناپذیری در Go و PHP 8.4، توابع بی‌اثر جانبی و بسته‌بودن عملیات (Money + Money = Money)، مرزهای مفهومی و مقدار کامل در برابر وسواس به نوع‌های ابتدایی، تله‌های برابری و hash (float، منطقهٔ زمانی، ارقام فارسی)، enum به‌عنوان مقدار، نگاشت ذخیره‌سازی (ستون‌های جاسازی‌شده، JSON، جدول وابسته، Scanner/Valuer، castهای Eloquent)، مقدارها در لبهٔ API و در رویدادها، و تست مقدارها با تست مبتنی بر ویژگی و fuzz. هدف یادگیری (Learning goal): برای هر مفهوم دامنه با دلیل تصمیم بگیرید Entity است یا Value؛ Entity Order و Value Objectهایش (OrderId، Money، Quantity، ShippingAddress، PhoneNumber، OrderLine) را در Go و Laravel طوری بسازید که نمونهٔ نامعتبر اصلاً نتواند وجود داشته باشد؛ آن‌ها را بدون نشت مدل ذخیره و سریال کنید؛ و ضدالگوها را در code review تشخیص بدهید.

این فصل گروه DD 02 (طراحی تاکتیکی) را باز می‌کند. فرض می‌کند فصل‌های راهبردی را خوانده‌اید: contextهای Sales، Fulfilment، Billing، Catalog و Identity در فروشگاه آنلاین ما (Bounded Context) و واژه‌هایشان (Ubiquitous Language). مبانی شیءگرای هویت در برابر برابری در مدل‌سازی شیءگرا آمده؛ این صفحه نگاه DDD است و خیلی جلوتر می‌رود. پرسشی که این صفحه صاحبش است: این شیء از چه نوعی است و چطور بسازمش که نتواند غلط باشد؟ بقیه را همسایه‌ها می‌گویند: کدام اشیا در یک تراکنش با هم عوض می‌شوند (Aggregates & Factories)، چرا رفتار باید روی همین اشیا باشد (Anemic vs Rich)، بارگذاری و ذخیره‌شان (Repositories، ماندگاری داده در طراحی)، منطقی که در هیچ‌کدام جا نمی‌شود (Domain, Application & Infrastructure Services) و آنچه هنگام تغییرشان منتشر می‌شود (Domain Events vs Integration Events). جزئیات UUID و ULID و Snowflake در تولید شناسه در مقیاس است.

نقشهٔ صفحه (Page map) ​

دنبال چه هستیدبروید به
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
چرا این تمایز ارزشش را داردچرا وجود دارد
Evans 2003، Fowler، Vernon، Whole Value کانینگهاماز کجا آمده
هویت در طول زمان، برابری با شناسهEntity
تغییرناپذیر، برابری با مقدار، جایگزین‌پذیرValue Object
«برایمان مهم است کدام‌یکی است؟»پرسش هویت
طبیعی یا جانشین، UUIDv7، چه کسی تولید می‌کند، OrderIdانتخاب و تولید هویت
اشیای همیشه‌معتبر، fail fast یا جمع‌کردن خطاهاInvariant و خوداعتبارسنجی
final readonly class، فیلدهای unexported، with-er، aliasingتغییرناپذیری
Money + Money = Money، تخصیصتوابع بی‌اثر جانبی و بسته‌بودن عملیات
Primitive obsession، Whole Value، مرزهای مفهومیمقدار کامل و مرزهای مفهومی
float، منطقهٔ زمانی، ارقام فارسی، کلید mapتله‌های برابری و hash
enum پشتیبانی‌شده، ثابت‌های تایپ‌دار Goenum به‌عنوان Value Object
OrderLine مقدار است یا Entity؟Entity ساخته از مقدارها؛ بحث OrderLine
ستون جاسازی‌شده، JSON، جدول وابسته، cast، Scanner/Valuerسازوکار: نگاشت ذخیره‌سازی
DTO، رویداد، پیامسازوکار: مقدارها در لبه
پیام‌های خطایی که می‌بینیدسازوکار: خطاها
کد کامل با تستGo، Laravel
VO تغییرپذیر، setter عمومی، VO با شناسه، Eloquent به‌جای Entityحل مسئله‌های کلاسیک
کدام ابزار برای کدام مفهومانتخاب
از monolith تا دادهٔ توزیع‌شدهدر معماری
تمرین عملیآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

دو آجر اصلی. هر سطر در فهرست مفاهیم باز می‌شود.

موجودیت (Entity)شیء مقداری (Value Object)
به زبان سادهچیزی که در طول زمان دنبالش می‌کنیمیک توصیف، یک اندازه، یک مبلغ
تعریف‌شده باهویت (یک شناسه)همهٔ ویژگی‌هایش
برابریشناسهٔ یکسان = همان چیز، حتی اگر همهٔ ویژگی‌ها فرق کنندویژگی‌های یکسان = برابر، حتی اگر دو نمونهٔ جدا باشند
تغییربا متدهایی که قاعده‌ها را پاس می‌دارند؛ چرخهٔ عمر داردهرگز؛ با یک نمونهٔ تازه جایگزین می‌شود
مثال در SalesOrder، Customer (در Identity)، Shipment (در Fulfilment)Money، Quantity، ShippingAddress، Email، OrderId، OrderStatus
شکل در Goاشاره‌گر *Order، فیلدهای unexported، SameAsstruct با فیلدهای unexported و comparable، ==، متدهایی که مقدار تازه برمی‌گردانند
شکل در PHP 8.4final class با ویژگی‌های public private(set)final readonly class با equals()
ذخیره به شکلردیف خودش با کلید اصلیستون‌هایی روی مالک، یک ستون JSON، یا ردیف‌های جدول وابسته

چک‌لیست Value Object (ویژگی‌هایی که Evans و Vernon برشمرده‌اند):

ویژگیبه زبان سادهمثال کوچکبدون آن چه خراب می‌شود
اندازه می‌گیرد، می‌شمارد یا توصیف می‌کند (Measures, quantifies, describes)می‌گوید چقدر یا چه نوع22.50 EUR، 3 واحد، تهران 12345-67890رفتار خانه ندارد و در سرویس‌ها پخش می‌شود
تغییرناپذیر (Immutable)بعد از ساخت عوض نمی‌شودprice.Add(tax) یک Money تازه برمی‌گرداندباگ aliasing: یک تغییر در دو سفارش دیده می‌شود
کلِ مفهومی (Conceptual whole)ویژگی‌هایی که با هم معنا دارندمبلغ + ارز، شروع + پایانکسی سنت یورو را با سنت دلار جمع می‌کند
جایگزین‌پذیر (Replaceable)تغییر = گذاشتن یک نمونهٔ تازهorder.ShipTo(newAddress)order.address.city = ... اعتبارسنجی را دور می‌زند
برابری مقداری (Value equality)با ویژگی‌های برابر، برابر استدو 22.50 EUR برابرندتکرار در مجموعه‌ها، کلید map خراب
بی‌اثر جانبی (Side-effect-free)عملیات فقط حساب می‌کنند و برمی‌گردانندAllocate(1,1,1)محاسبه‌ای که چیزی هم می‌نویسد، تست‌ناپذیر است
خوداعتبارسنج (Self-validating)نمی‌تواند در حالت نامعتبر وجود داشته باشدNewQuantity(0) شکست می‌خوردهر فراخواننده دوباره چک می‌کند و بعضی یادشان می‌رود

مقدارها کجا زندگی می‌کنند (جزئیات در سازوکار):

مفهومنوعذخیره‌سازیشکل در API / رویداد
OrderIdمقداری که نقش هویت داردستون uuid، کلید اصلیرشتهٔ "id": "0190..."
Moneyمقداردو ستون: total_minor bigint، total_currency char(3){"amount_minor": 2250, "currency": "EUR"}
ShippingAddressمقداریک ستون jsonbفیلدهای صریح DTO
OrderLine x Nمقدار درون Entityجدول وابستهٔ order_lines با کلید (order_id, sku)آرایه‌ای از DTOها
OrderStatusمقدار enumtext با CHECK"status": "placed"
OrderEntityردیفی در orders + خط‌هایشOrderDTO، OrderPlacedV1

چرا وجود دارد ​

نرم‌افزاری که یک کسب‌وکار را مدل می‌کند بیشتر با دو جور چیز سروکار دارد: چیزهایی که کسب‌وکار دنبالشان می‌کند (این سفارش، آن مشتری، این بسته) و چیزهایی که آن‌ها را توصیف می‌کنند (یک مبلغ، یک نشانی، یک بازهٔ تاریخ). حرف Evans این است که این دو رفتار متفاوت می‌خواهند و چسباندن هویت به همه‌چیز هزینه دارد: "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."

همه‌چیز را Entity دیدنجداکردن Entity از Value
هر شیء شناسه، جدول و repository می‌گیردفقط چیزهای دارای چرخهٔ عمر شناسه می‌گیرند
برابری همه‌جا یعنی «همان ردیف»برابری با معنای کسب‌وکار جور است
ویژگی‌ها نوع ابتدایی با setter هستندویژگی‌ها نوع‌های کوچک با قاعده‌اند
اعتبارسنجی در controller و سرویس‌ها پخش استاعتبارسنجی در سازندهٔ مقدار است
اشیای تغییرپذیر مشترک باگ aliasing می‌سازندمقدارها تغییرناپذیرند و اشتراکشان امن است
تست‌ها پایگاه داده می‌خواهندمقدارها مثل تابع خالص تست می‌شوند

تصویر روزمره، که در کل صفحه برمی‌گردیم سراغش. یک اسکناس و یک گذرنامه را در نظر بگیرید. اگر دوستتان ۱۰ یورو به شما بدهکار است، برایتان مهم نیست کدام اسکناس ۱۰ یورویی برگردد: هر اسکناسی با همان ارزش بدهی را صاف می‌کند. این یک مقدار است. گذرنامه فرق دارد: ممکن است دو گذرنامه نام و تاریخ تولد یکسان داشته باشند، ولی برای مرزبانی مهم است کدام گذرنامه است، آن را در تمدید و عوض‌شدن عکس دنبال می‌کند و چرخهٔ عمر دارد (صادر، معتبر، منقضی، باطل). این یک Entity است. (بانک مرکزی شمارهٔ سریال اسکناس را دنبال می‌کند: در context آن، اسکناس هست Entity. همان چیز، context دیگر.)

سه بدفهمی رایج، همین اول ​

  1. «Entity یعنی جدول، Value Object یعنی ستون.» نه. Fowler هشدار می‌دهد "Entity is often used to represent a database table or an object that corresponds to a database table"؛ در DDD یعنی شیء دارای هویت. یک Value Object می‌تواند جدول خودش را داشته باشد (خط‌های سفارش) و یک Entity می‌تواند در یک سند JSON ذخیره شود.
  2. «Value Object همان DTO است.» نه. حدود سال ۲۰۰۰ بعضی کتاب‌های J2EE به DTO می‌گفتند value object؛ Fowler می‌گوید این کاربرد "has mostly disappeared by now". Value Object در DDD رفتار و invariant دارد؛ DTO هیچ‌کدام را ندارد.
  3. «Entity بودن ویژگی خود آن چیز است.» نه. تصمیمی است که مدل در یک Bounded Context می‌گیرد. نشانی در Sales مقدار است و در یک context ثبت نشانی‌های پستی می‌تواند Entity باشد.

از کجا آمده ​

  • Ward Cunningham، Whole Value. ایدهٔ اشیایی که یک کمیت کامل دامنه را نشان می‌دهند، نه عدد و رشتهٔ خام. Vernon هنگام جداکردن «ویژگی از نوع مقدار» از "a simple attribute such as a string or numeric type ... as does Ward Cunningham when describing Whole Value" به او ارجاع می‌دهد (Vernon، Implementing DDD، یادداشت فصل ۱۰، نمونهٔ رایگان ناشر). متن اصلی کانینگهام را نخوانده‌ایم و فقط از طریق Vernon نقلش می‌کنیم.
  • Martin Fowler، Patterns of Enterprise Application Architecture (صفحه‌های کاتالوگ با تاریخ ۵ مارس ۲۰۰۳). الگوهای Value Object، Money ("it's always puzzled me that money isn't actually a first class data type in any mainstream programming language") و الگوهای ذخیره‌سازی همین صفحه را فهرست کرد: Embedded Value، Serialized LOB و Dependent Mapping.
  • Eric Evans، Domain-Driven Design (۲۰۰۳). Entity، Value Object و Service را آجرهای اصلی کرد و الگوهای طراحی نرم (Supple Design) را افزود که این صفحه به آن‌ها تکیه دارد: Side-Effect-Free Functions، Assertions، Conceptual Contours و Closure of Operations. DDD Reference رایگان (۲۰۱۵) دوباره بیانشان می‌کند. یادداشت Evans Classification از Fowler (۱۴ دسامبر ۲۰۰۵) این سه‌گانه را خلاصه می‌کند.
  • Vaughn Vernon، Implementing Domain-Driven Design (۲۰۱۳). فصل ۵ (Entities) و فصل ۶ (Value Objects). فهرست مطالب نمونهٔ رایگان ناشر قلمرو را نشان می‌دهد: برای هویت "User Provides Identity"، "Application Generates Identity"، "Persistence Mechanism Generates Identity"، "Another Bounded Context Assigns Identity"، "Surrogate Identity"، "Identity Stability"؛ و برای مقدارها "Measures, Quantifies, or Describes"، "Immutable"، "Conceptual Whole"، "Replaceability"، "Value Equality"، "Side-Effect-Free Behavior"، "Standard Types Expressed as Values" و پنج گزینهٔ ذخیره‌سازی از "ORM and Single Value Objects" تا "ORM and Enum-as-State Objects". خلاصهٔ او از مطالعهٔ موردی: تیم "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 (۱۴ نوامبر ۲۰۱۶). بیان کوتاه امروزی: "Objects that are equal due to the value of their properties ... are called value objects"، به‌اضافهٔ استدلال باگ aliasing برای تغییرناپذیری.
  • زبان‌ها هم رسیدند. PHP 8.1 ویژگی‌های readonly و enum را آورد، 8.2 کلاس‌های readonly، 8.4 property hooks و دید نامتقارن (asymmetric visibility)، و 8.5 (منتشرشده ۲۰ نوامبر ۲۰۲۵) clone() با بازنویسی ویژگی‌ها، که یادداشت انتشار می‌گوید الگوی with-er را "simple for readonly classes" می‌کند. Go از نسخهٔ 1.0 struct مقایسه‌پذیر داشته و از 1.18 generics. Eloquent در Laravel cast سفارشی و Value Objectهای Castable گرفت؛ HasUuids در Laravel 13 به‌طور پیش‌فرض "will generate UUIDv7 identifiers".

فهرست مفاهیم ​

هر بلوک همین ترتیب را دارد: به زبان ساده، باور غلط رایج، تعریف دقیق، timeline، سناریوی واقعی، جدول مقایسه، و راه درست در کد.

Entity حیاتی ​

به زبان ساده: Entity چیزی است که آن را همان یکی نگه می‌داریم در حالی که جزئیاتش عوض می‌شود، مثل سفارشی که از پیش‌نویس تا ارسال‌شده پیش می‌رود.

بدفهمی رایج: «Entity هر چیزی است که ستون id دارد.» خیلی از اشیا فقط چون ORM می‌خواهد id می‌گیرند. محک این نیست که «id دارد؟» بلکه این است که «اگر دو نمونهٔ شبیه هم را قاطی کنیم، کسب‌وکار به مشکل می‌خورد؟»

تعریف: Evans: "Many objects represent a thread of continuity and identity, going through a lifecycle, though their attributes may change." نسخه‌ای که می‌پیچد: "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." و جمله‌ای که بحث‌ها را تمام می‌کند: "The model must define what it means to be the same thing." Fowler اضافه می‌کند که Entityها گونه‌ای رایج از شیء ارجاعی (Reference object) هستند و مقدارها برابری را بازنویسی می‌کنند "while entities usually don't".

text
     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.

سناریوی واقعی: دو مشتری به نام «سارا احمدی» در تهران با دامنهٔ ایمیل یکسان نباید ادغام شوند (context هویت). پشتیبان می‌گوید «سفارش دیروز»: سیستم باید آن را با شماره پیدا کند، هرچند وضعیت، مبلغ و نشانی‌اش عوض شده. بازپرداخت باید به همین پرداخت برود، نه به پرداخت دیگری با همان مبلغ در همان روز.

هر فناوری هویت را چطور بیان می‌کند:

فناوریسازوکار هویتبرابری پیش‌فرضآنچه اضافه می‌کنید
Goاشاره‌گر *Order در حافظه؛ فیلد OrderID== روی اشاره‌گر = همان متغیر؛ روی struct = همهٔ فیلدهاSameAs(other) با مقایسهٔ شناسه
PHP 8.4handle شیء=== همان نمونه؛ == همان کلاس و ویژگی‌های برابرsameAs() با مقایسهٔ OrderId
Eloquentکلید اصلی + جدول + اتصال$a->is($b) "the same primary key, table, and database connection" را مقایسه می‌کنداگر منطق غنی است، نگاشت به Order دامنه
PostgreSQLPRIMARY KEYهویت ردیفکلید تغییرناپذیر که دوباره مصرف نمی‌شود

راه درست: Entityها را کوچک و رفتاری نگه دارید: هویت، وضعیت چرخهٔ عمر، متدهای نیت‌نما (Go: AddLine، ShipTo، Place) و Value Object برای هر چیز توصیفی. شناسه را از بیرون سازنده بدهید تا تلاش دوباره (retry) بتواند همان را به کار ببرد (هویت). setter عمومی ممنوع (ضدالگو).

Value Object حیاتی ​

به زبان ساده: Value Object یک توصیف کوچک و تغییرناپذیر است، مثل «22.50 EUR» یا «3 واحد»؛ دو تا با محتوای یکسان، ساده برابرند.

بدفهمی رایج: «Value Object یعنی struct بدون id.» این فقط نبودِ هویت است. 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." Value Object معنا و رفتار دارد: Money ارزش را می‌شناسد، فقط با همان ارز جمع می‌شود و بدون گم‌کردن یک سنت تخصیص می‌دهد.

تعریف: 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." و از Evans Classification نوشتهٔ Fowler: "Objects that matter only as the combination of their attributes. Two value objects with the same values for all their attributes are considered equal."

text
     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)

سناریوی واقعی: قیمت، جمع، تخفیف، مالیات (Money، Percentage)؛ موجودی و تعداد سفارش (Quantity)؛ بازهٔ کمپین و بازهٔ تحویل (DateRange)؛ نشانی ارسال و صورت‌حساب؛ اطلاعات تماس (Email، PhoneNumber)؛ و خود شناسه‌ها (OrderId مقداری است که نقش هویت یک Entity را بازی می‌کند).

پشتیبانی زبان‌ها از مقدار:

زبانآجرهای ساخت Value Objectتله
Gostruct با فیلدهای unexported، سازندهٔ NewX، receiver مقداری، == وقتی همهٔ فیلدها comparable باشندslice یا map درون struct آن را غیرقابل‌مقایسه می‌کند؛ == روی time.Time منطقه و خوانش monotonic را هم مقایسه می‌کند
PHP 8.4final readonly class، سازندهٔ private + سازنده‌های نام‌دار، enumreadonly جلوی «تغییرپذیری درونی» (interior mutability) اشیای درونش را نمی‌گیرد؛ hookها "incompatible with readonly properties" هستند
PHP 8.5clone($this, ['field' => $v]) برای with-erLaravel 13 به PHP 8.3 نیاز دارد، پس در کد مشترک به 8.5 تکیه نکنید
EloquentCastsAttributes، Castable::castUsing، enum cast، Attribute::makeمثال مستندات شیء cast را درجا تغییر می‌دهد؛ با مقدار readonly نمونهٔ تازه می‌گذارید
PostgreSQLCREATE DOMAIN، نوع مرکب، CHECKdomain ذخیره‌سازی را محدود می‌کند؛ به کد شما رفتار نمی‌دهد

راه درست: مقدار را اولین ابزارتان کنید. در Go: type Money struct{ minor int64; currency Currency } به‌اضافهٔ NewMoney و متدهایی که Money برمی‌گردانند. در PHP: final readonly class Money با سازندهٔ private و ofMinor() / parse(). کد در Go و Laravel.

پرسش هویت حیاتی ​

به زبان ساده: بپرسید «اگر این یکی را با یکی دیگر که دقیقاً همین شکل است عوض کنم، کسی در کسب‌وکار اهمیت می‌دهد؟» اگر بله، Entity؛ اگر نه، مقدار.

بدفهمی رایج: «اگر عوض می‌شود، Entity است.» مقدارها چیزهایی را توصیف می‌کنند که مدام عوض می‌شوند (نشانی مشتری، جمع سفارش)؛ نگه‌دارنده با جایگزین‌کردن مقدار عوض می‌شود. محک، تغییر نیست؛ پیوستگی هویت است.

تعریف: تصمیم برای هر Bounded Context جداگانه گرفته می‌شود، با پرسیدن اینکه متخصص دامنه از «همان» چه منظوری دارد. قاعدهٔ سرانگشتی Vernon برای اجزای یک aggregate: "Cases where instances can be completely replaced point to the use of a Value Object rather than an Entity." و: "Choose to model a contained Aggregate part as a Value Object rather than an Entity whenever possible."

1. Must we tell two equal-looking ones apart,or follow one through changes over time?"Is this the same order as yesterday's?"2. Fully described by its attributes, andreplaced as a whole when it changes?"Do we care which 10 EUR note it is?" No.3. Is it an activity, not a thing?"Calculate shipping cost", "transfer funds"yesyesyesnononoEntitystable id, equality by idlifecycle, guarded mutationOrder, Customer, ShipmentValue objectimmutable, equality by valueself-validating, side-effect-freeMoney, Quantity, Address,Email, DateRange, OrderIdDomain servicestateless operation in theubiquitous languageStill unclear? Ask the domain expert which question matters in THIS bounded context.An Address is a value in Sales, an entity in a postal-registry context; a Seat is a value at a cinema, an entity on a plane.

نمودار بالا سه پرسش را به ترتیب می‌پرسد: آیا باید دو نمونهٔ شبیه هم را از هم تشخیص دهیم یا یکی را در طول تغییرات دنبال کنیم (Entity)؛ آیا با ویژگی‌هایش کامل توصیف می‌شود و یکجا جایگزین می‌شود (Value Object)؛ آیا اصلاً یک فعالیت است نه یک چیز (Domain Service). اگر هنوز روشن نیست، از متخصص دامنه بپرسید کدام پرسش در همین context مهم است.

text
     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).

سناریوی واقعی (یک واژه، پاسخ‌های مختلف):

مفهومcontextی که در آن مقدار استcontextی که در آن Entity استچرا فرق دارد
نشانی (Address)Sales: این سفارش کجا ارسال شودثبت نشانی پستی، برنامه‌ریزی مسیر تحویلثبت‌کننده یک نشانی را در تغییر نام و اصلاح geocode دنبال می‌کند
صندلی (Seat)سینما با صندلی آزاد در هر ردیفهواپیمایی: صندلی 14C پرواز IR712ایرلاین یک صندلی مشخص می‌فروشد
پول (Money)همه‌جا در Sales و Billingبانک مرکزی که شمارهٔ سریال را دنبال می‌کندسریال فقط برای بانک مهم است
قیمت کالاخط سفارش در Sales: قیمت لحظهٔ سفارشCatalog: PriceListEntry با اعتبار زمانی و auditCatalog آن را در طول زمان مدیریت می‌کند
مشتریفاکتور Billing: عکس فوری «صورت‌حساب به»Identity: حساب کاربریBilling همان چیزی را می‌خواهد که هنگام صدور درست بود

راه درست: پاسخ را در واژه‌نامهٔ context (Ubiquitous Language) و در خود نوع بنویسید: یک نوع مقداری بدون شناسه، یا یک Entity با شناسهٔ تایپ‌دار.

انتخاب و تولید هویت حیاتی ​

به زبان ساده: Entity شناسه‌ای می‌خواهد که هرگز عوض نشود، یکتا باشد و همان وقتی که لازمش دارید موجود باشد؛ اینکه چه کسی بسازدش و با چه قالبی، تصمیم طراحی است.

بدفهمی رایج: «auto-increment پایگاه داده همان هویت است.» یکی از گزینه‌هاست با یک عیب بزرگ: شناسه تا INSERT وجود ندارد، پس بدون رفت‌وبرگشت نمی‌توانید آن را در رویداد، کلید idempotency یا نوشتن دوم همان use case بگذارید، و اگر بیرون نشان داده شود حجم کسب‌وکار را لو می‌دهد.

تعریف: 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 چهار منبع برمی‌شمارند (کاربر، برنامه، سازوکار ماندگاری، context دیگر) و دو عنوان دیگر: "Surrogate Identity" و "Identity Stability"؛ به برداشت ما، هویت جانشین (Surrogate identity) کلید پایگاه داده‌ای است که کنار شناسهٔ دامنه نگه داشته می‌شود و پایداری هویت (Identity stability) یعنی شناسه هرگز عوض نمی‌شود. RFC 9562 نسخهٔ ۷ را تعریف می‌کند: "UUIDv7 features a time-ordered value field derived from the widely implemented and well-known Unix Epoch timestamp source".

منبع / قالبمثالکی در دسترس استمزیتعیب
کلید طبیعی دامنه (Natural key)ISBN، کد ملی، IBANپیش از ساختمعنادار، خودش تکرار را می‌گیردممکن است عوض شود، غلط تایپ شود یا دادهٔ شخصی باشد
کاربر می‌دهدنام کاربری، کد کوپنپیش از ساختانسان‌پسندچک یکتایی، تغییر نام
sequence پایگاه داده / AUTO_INCREMENTorders.id = 1042بعد از INSERTکوچک، مرتبدیر؛ حدس‌زدنی؛ میان shardها سخت
UUIDv4 در برنامه122 بیت تصادفیپیش از ماندگاریهر جا تولید می‌شوددرج تصادفی در index (locality)
UUIDv7 / ULID در برنامه0190f3c2-...پیش از ماندگاریمرتب زمانی، مناسب indexزمان ساخت را لو می‌دهد
context دیگر می‌دهدشناسهٔ پرداخت از PSPبعد از پاسخ آن سیستمبا منبع هم‌بسته استوابستگی به آن سیستم
text
     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.

سناریوی واقعی: شمارهٔ سفارشی که به مشتری نشان داده می‌شود («IR-2026-004211») یک مقدار نمایشی جداست، نه کلید اصلی، تا بشود قالبش را عوض کرد یا کوتاهش کرد. شناسهٔ مرسوله که شرکت حمل می‌دهد، هویتی از «context دیگر» است و به شکل مقدار روی Shipment ما ذخیره می‌شود. CustomerId در Sales یک مقدار ارجاعی به context هویت است، هرگز اشاره‌گر به شیء (Aggregates).

شناسهٔ تایپ‌دار (Typed id). شناسه را در نوع مقداری خودش بپیچید (OrderId، CustomerId) تا کامپایلر cancel(customerId) را جایی که OrderId لازم است رد کند و parse و قالب‌بندی یک جا باشد.

راه درست: در Go، NewOrderID(now) یک UUIDv7 را با crypto/rand طبق RFC 9562 می‌سازد (snippet پایین). در Laravel، OrderId::generate() دور Str::uuid7() پیچیده شده؛ روی مدل Eloquent، trait HasUuids به‌طور پیش‌فرض UUIDv7 می‌سازد. مقایسهٔ عمیق‌تر قالب‌ها و رفتار indexشان: تولید شناسه در مقیاس.

Invariant و خوداعتبارسنجی حیاتی ​

به زبان ساده: Value Object قاعده‌هایش را همان لحظهٔ ساخت چک می‌کند، پس هر نمونه‌ای که وجود دارد معتبر است؛ کسی لازم نیست دوباره چک کند.

بدفهمی رایج: «اعتبارسنجی جایش در controller یا form request است.» اعتبارسنجی درخواست شکل ورودی یک endpoint را چک می‌کند. Invariantها قاعده‌های دامنهاند که باید در هر مسیری برقرار باشند: HTTP، مصرف‌کنندهٔ صف، import از CLI، fixture تست. قاعده را جایی بگذارید که هیچ مسیری نتواند دورش بزند.

تعریف: الگوی Assertions از Evans: "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." شیء همیشه‌معتبر (Always-valid یا self-validating) invariantهایش را در سازنده (یا سازنده‌های نام‌دار) و در هر عملیاتی که نمونهٔ تازه می‌سازد اعمال می‌کند؛ هیچ راهی برای گرفتن نمونهٔ نامعتبر نیست جز کد آگاهانهٔ بازسازی (rehydration).

شکست سریع (Fail fast) یا جمع‌کردن خطاها؟ برای یک مقدار تکی (یک تعداد)، اولین خطا را برگردانید. برای مقداری که از یک فرم ساخته می‌شود (یک نشانی)، توصیهٔ Fowler در Replacing Throwing Exceptions with Notification in Validations صدق می‌کند: "If you're validating some data, you usually shouldn't be using exceptions to signal validation failures." همهٔ مشکل‌ها را جمع کنید و با هم گزارش دهید (الگوی Notification)؛ ShippingAddress ما یک خطا برمی‌گرداند که همهٔ مشکل‌ها را فهرست می‌کند.

text
     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.

سناریوی واقعی: import عمده‌فروشی (B2B) که controller را دور زد و خط با تعداد صفر ساخت؛ نشانی با کد پستی ۹ رقمی که باعث شد API شرکت حمل یک دستهٔ کامل را رد کند؛ درصد ۱۲۰٪ که به‌عنوان تخفیف اعمال شد.

روشقاعده کجا زندگی می‌کندچه کسی می‌تواند دورش بزندمناسب برای
فقط اعتبارسنجی form request / handlerلبههر مسیر غیر HTTPشکل ورودی، پیام‌های UX
فقط CHECK / DOMAIN پایگاه دادهذخیره‌سازیکدی که ذخیره نمی‌کند یا پایگاه دادهٔ دیگرآخرین خط دفاع
Value Object خوداعتبارسنجسازندهفقط بازسازی صریحinvariantهای دامنه
هر سه، با VO به‌عنوان منبع حقیقتلایه‌لایههیچ‌کسسیستم‌های production

راه درست: در Go، NewX مقدار (T, error) برمی‌گرداند با خطاهای sentinel (errors.Is(err, ErrInvalidQuantity))؛ در PHP سازنده یک استثنای دامنه (InvalidValue) پرتاب می‌کند. پیام‌ها را به زبان همه‌گیر بنویسید و در لبه به HTTP 422 نگاشت کنید.

تغییرناپذیری حیاتی ​

به زبان ساده: مقدار بعد از ساخت هرگز عوض نمی‌شود؛ برای «تغییر» یکی تازه می‌سازید و جای قبلی می‌گذارید.

بدفهمی رایج: «تغییرناپذیری برای کارایی یا threadهاست.» آنجا هم کمک می‌کند، ولی دلیل دامنه‌ای‌اش aliasing است: وقتی دو نگه‌دارنده یک مقدار تغییرپذیر را شریکند، تغییر از یکی در دیگری دیده می‌شود. 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."

تعریف: Value Object هیچ عملیاتی ندارد که حالت قابل‌مشاهده‌اش را عوض کند؛ مقدارهای مشتق‌شده به شکل نمونهٔ تازه برمی‌گردند. در PHP 8.2 به بعد: "Marking a class as readonly will add the readonly modifier to every declared property, and prevent the creation of dynamic properties." در Go کلیدواژهٔ readonly نداریم؛ تغییرناپذیری با فیلدهای unexported، یک سازنده، receiverهای مقداری که مقدار تازه برمی‌گردانند و کپی دفاعی slice و map به دست می‌آید.

text
     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.

روش‌ها در هر زبان:

روشGoPHP 8.4PHP 8.5
جلوگیری از نوشتنفیلدهای unexported؛ بدون setterfinal readonly classهمان
ساخت معتبرNewX(...) (X, error)سازندهٔ private + سازنده‌های نام‌دارهمان
with-erreceiver مقداری: func (l OrderLine) WithQuantity(q Quantity) OrderLine { l.quantity = q; return l }return new self(...all fields...)return clone($this, ['quantity' => $q]);
مجموعه‌های درونیslices.Clone(x) برگردانید؛ آرایهٔ پشتی را بیرون ندهیدآرایه‌ها هنگام نوشتن کپی می‌شوند؛ اشیای درونشان نههمان
جلوگیری از تغییر در زیرکلاسارث‌بری نداریمfinalهمان

clone با بازنویسی در PHP 8.5، از یادداشت انتشار:

php
// 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,
    ]);
}

سناریوی واقعی: شیء «نشانی پیش‌فرض» که در یک worker طولانی‌عمر (Laravel Octane، یک سرویس Go) در حافظه cache شده و میان درخواست‌ها شریک بوده و ویرایش یک درخواست به درخواست دیگر نشت کرده؛ نمونهٔ Money که به تابع تخفیف داده شد و آن را تغییر داد، و جمع سبد خرید با جمع فاکتور نخواند.

راه درست: OrderLine.WithQuantity در Go و ShippingAddress::withLine2() در PHP را ببینید. هشدار راهنمای PHP را جدی بگیرید: "readonly properties do not preclude interior mutability"؛ درون مقدار readonly فقط چیزهای تغییرناپذیر نگه دارید (scalar، enum، مقدارهای readonly دیگر).

توابع بی‌اثر جانبی و بسته‌بودن عملیات حیاتی ​

به زبان ساده: متدهای یک مقدار فقط حساب می‌کنند و جواب برمی‌گردانند؛ و هر جا جور باشد، جمع دو پول یک پول است، پس عملیات را بدون مفهوم تازه زنجیر می‌کنید.

بدفهمی رایج: «تقسیم هم یک عملیات دیگر است.» پول تقسیم بر ۳ پول نیست (10.00 / 3 = 3.333...). اگر به‌زور بسته‌اش کنید، سنت گم می‌شود. عملیات بستهٔ «تقسیم پول» تخصیص (Allocation) است که بخش‌هایی برمی‌گرداند که جمعشان دقیقاً کل است.

تعریف: الگوی Side-Effect-Free Functions از Evans: "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." و "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."

text
     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)

سناریوی واقعی: مالیات ۹٪ روی 12.50 یورو می‌شود 1.125 یورو و باید با یک قاعدهٔ اعلام‌شده به واحد خرد گرد شود (ما از «نیمه به دور از صفر» استفاده می‌کنیم)؛ هزینهٔ ارسالی که در marketplace میان فروشنده‌ها پخش می‌شود؛ طرح اقساط ۱٬۰۰۰٬۰۰۰ ریالی در ۳ قسط.

عملیاتبسته؟امضانکته
جمع / تفریقبلهMoney x Money -> Moneyهمان ارز یا خطا
ضرب در Quantityنیمه‌بستهMoney x Quantity -> Moneyآرگومان فرق دارد، خروجی همان نوع است
درصدی ازنیمه‌بستهMoney x Percentage -> Moneyقاعدهٔ گردکردن را نام ببرید
تخصیصبسته روی مجموعهMoney x ratios -> []Moneyجمع بخش‌ها برابر کل
تقسیمنهMoney / int -> ?فراهمش نکنید
مقایسهبسته نیست (bool)Money x Money -> boolفقط با همان ارز

راه درست: Money.Add، Sub، Times(Quantity)، PercentOf(Percentage)، Allocate(ratios...) در Go؛ همین‌ها در PHP. فرمان‌ها (Order.Place) فقط خطا برمی‌گردانند، هرگز دادهٔ دامنه.

مقدار کامل و مرزهای مفهومی مهم ​

به زبان ساده: ویژگی‌هایی را که با هم معنا دارند در یک نوع جمع کنید (مبلغ + ارز، شروع + پایان) و نوع‌هایتان را جایی ببرید که کسب‌وکار خط می‌کشد، نه جایی که پایگاه داده.

بدفهمی رایج: «نوع‌های کوچک زیاده‌روی است؛ string کافی است.» string برای شمارهٔ تلفن «سلام» را هم می‌پذیرد؛ float برای قیمت، یورو را با ریال جمع می‌کند. Fowler: جایگزینی نوع ابتدایی با Value Object "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)." بوی مخالفش وسواس به نوع ابتدایی (Primitive obsession) است (Code Smells).

تعریف: مقدار کامل (Whole value) یک مفهوم کامل دامنه را نمایش می‌دهد. الگوی Conceptual Contours از Evans: "Decompose design elements (operations, interfaces, classes, and aggregates) into cohesive units, taking into consideration your intuition of the important divisions in the domain." و دربارهٔ خیلی ریز بریدن هم هشدار می‌دهد: "Half of a uranium atom is not uranium."

text
     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 CustomerID

سناریوی واقعی (مرز کجا می‌گذرد):

خیلی ریز (نوع ابتدایی)مقدار کاملخیلی درشت
amount float64, currency stringMoneyOrderTotals با 14 فیلد اختیاری
start, end time.TimeDateRange با Contains و OverlapsCampaign که فقط برای تاریخ‌هایش به کار می‌رود
phone stringPhoneNumber (E.164)ContactInfo که تلفن، ایمیل و رضایت را قاطی کرده
city, postal, line1 ...ShippingAddressCustomer که نشانی‌ای را حمل می‌کند که مالکش نیست
rate int // percent? bp?Percentage با واحد basis pointتوده‌ای به نام PricingRule

راه درست: مقدارها را یکی‌یکی همان جایی وارد کنید که باگ هست (اول پول، بعد شناسه‌ها، بعد اطلاعات تماس). Vernon مقدارهای پرکاربرد مشترک را نوع استاندارد (Standard Type) می‌نامد (ارزها، کد کشورها)؛ در کد ما Currency و OrderStatus این نقش را دارند. کلِ مفهومی (Conceptual whole) همان چیزی است که مبلغ و ارز را از هم جدا نمی‌گذارد.

تله‌های برابری و hash حیاتی ​

به زبان ساده: برابری مقداری فقط به خوبی فیلدهایی است که مقایسه می‌کنید؛ float، منطقهٔ زمانی، گونه‌های حروف و خط ارقام باعث می‌شوند مقدارهای «یکسان» متفاوت دیده شوند (یا برعکس).

بدفهمی رایج: «== کافی است.» در Go، == روی struct دارای time.Time منطقه و ساعت monotonic را هم مقایسه می‌کند؛ روی struct دارای slice کامپایل نمی‌شود؛ و از طریق interface در زمان اجرا panic می‌کند. در PHP، == دو شیء را برابر می‌داند "if they have the same attributes and values (values are compared with ==), and are instances of the same class"، با قاعده‌های شل == برای هر ویژگی.

تعریف: برابری یک مقدار باید (۱) روی شکل متعارف (Canonical form) تعریف شود که هنگام ساخت تولید می‌شود، و (۲) با hash سازگار باشد (کلید map در Go؛ کلید آرایه در PHP شکل رشته‌ای می‌خواهد). Fowler: "values override the equality method (and thus hash) while entities usually don't."

text
     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 construction

راهنمای Go صریح می‌گوید: "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". راهنمای PHP دربارهٔ float: "Floating-point numbers have limited precision." پیوست ۱۵ استاندارد یونیکد قول می‌دهد "When implementations keep strings in a normalized form, they can be assured that equivalent strings have a unique binary representation"، ولی «ي» عربی (U+064A) و «ی» فارسی (U+06CC)، «ك» عربی (U+0643) و «ک» (U+06A9)، و ارقام فارسی زیر نرمال‌سازی NFC یا NFKC هم‌ارز نیستند (با unicodedata پایتون آزمودیم)؛ سیستم فارسی‌زبان باید خودش تصمیم بگیرد و یکسان‌سازی خودش را اعمال کند. جزئیات سطح متن: Bits, Bytes & Text Encoding.

تلهGoPHPدرمان درون مقدار
مبلغ floatجمع float64 منحرف می‌شودجمع float منحرف می‌شودواحد خرد صحیح؛ اعشار را به شکل رشته parse کنید
مقدار زمان== منطقه + monotonic را مقایسه می‌کندDateTime == لحظه را؛ === نمونه راUTC یا فیلدهای تاریخ مدنی ذخیره کنید؛ با Equal مقایسه کنید
فیلد غیرقابل‌مقایسهفیلد slice/map: خطای کامپایل؛ از طریق any: panicنداردمقدارها را تخت نگه دارید؛ یا Equals و کلید رشته‌ای بنویسید
حروف بزرگ و فاصلهمقایسهٔ بایت‌به‌بایتمقایسهٔ بایت‌به‌بایتدر سازنده نرمال کنید
ارقام و حروف فارسی/عربیruneها فرق دارندcode pointها فرق دارندجدول نگاشت صریح هنگام ساخت
enum در برابر stringثابت تایپ‌دار در برابر رشتهٔ خامcase در برابر 'placed'یک بار در لبه parse کنید

راه درست: در سازنده متعارف کنید (PhoneNumber شکل E.164 را نگه می‌دارد، Email دامنه را کوچک می‌کند، DateRange تاریخ مدنی UTC نگه می‌دارد)، بعد == در Go یا equals() در PHP شکل‌های متعارف را مقایسه می‌کند. برابری و رفتار کلید map را صریح تست کنید (تست‌ها).

enum به‌عنوان Value Object مهم ​

به زبان ساده: وضعیت یا ارز یک مقدار است با مجموعهٔ ثابتی از حالت‌ها؛ آن مجموعه را یک نوع کنید و قاعده‌های مربوط را رویش بگذارید.

بدفهمی رایج: «enum فقط ثابت‌های نام‌دار است.» در PHP: "Enums (both Pure Enums and Backed Enums) may contain methods, and may implement interfaces"؛ در Go ثابت تایپ‌دار می‌تواند متد داشته باشد. پس enum یک Value Object کامل با رفتار است (CanCancel()، MinorUnits()).

تعریف: Value Object شمارشی نوعی مقداری است با مجموعهٔ بسته‌ای از نمونه‌ها. enumهای پشتیبانی‌شده (Backed enum) در PHP به ذخیره‌سازی رفت‌وبرگشت دارند: from() برای مقدار ناشناخته "will throw a ValueError" و tryFrom() "will return null". Go کلیدواژهٔ enum ندارد؛ از نوع نام‌دار، ثابت‌های iota که از ۱ شروع می‌شوند (تا مقدار صفر نامعتبر باشد)، متد String() و یک تابع Parse استفاده کنید.

text
     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.

سناریوی واقعی: وضعیت سفارش، روش پرداخت، ارز، سرعت ارسال، طبقهٔ مالیاتی. فهرست مطالب Vernon حالت ذخیره‌سازی‌اش را "ORM and Enum-as-State Objects" می‌نامد.

نیازPHP 8.4GoLaravel / SQL
مجموعهٔ بستهenum OrderStatus: stringtype OrderStatus uint8 + iotaCHECK (status IN (...)) یا نوع enum در PostgreSQL
رفتارمتد روی enumمتد روی نوعندارد
parsefrom / tryFromParseOrderStatusenum cast در Eloquent: 'status' => OrderStatus::class
آرایه‌ای از enumAsEnumCollection::of(...)[]OrderStatusستون JSON

راه درست: Currency (enum در PHP با minorUnits()، struct در Go از یک registry) و OrderStatus (enum در PHP با canCancel()، ثابت تایپ‌دار در Go با CanCancel()).

Entity ساخته از مقدارها؛ بحث OrderLine مهم ​

به زبان ساده: یک Entity خوب پوستهٔ نازکی از هویت و چرخهٔ عمر است دور تعداد زیادی مقدار؛ پرسش باز معمولاً این است که اجزایش (مثل خط‌های سفارش) مقدارند یا Entityهای کوچک.

بدفهمی رایج: «هر چیزی که جدول خودش را دارد باید Entity باشد.» ذخیره‌سازی تصمیم نمی‌گیرد. Vernon می‌گوید ممکن است ORM یک مجموعه از مقدارها را به ردیف‌های دارای id مجبور کند ("it must model collections of Values as database entities")، ولی این جزئیات ماندگاری است.

تعریف: Entity مقدارها را به‌عنوان ویژگی نگه می‌دارد و یکجا جایگزینشان می‌کند. یک جزء Entity وقتی مقدار است که بشود کامل جایگزینش کرد و چرخهٔ عمر خودش را نداشته باشد؛ وقتی Entity محلی است که چیزی باید آن را جداگانه در طول زمان دنبال کند.

Order (entity, aggregate root)id: OrderId (UUIDv7, value)customer: CustomerId (reference to Identity)currency: Currency status: OrderStatus (enum)AddLine, ShipTo, Place, Total, SameAsequality: by id only; mutable through methodsShippingAddress (value)recipient, line1, line2, city,province, postalCode (10 digits IR),country, phoneOrderLine (value) x Nsku: SKU (from Catalog)quantity: Quantity (1..50)unitPrice: MoneyplacedAt (instant, UTC)set once by Place(now)stored as timestamptzshown in Asia/Tehran at the edgePhoneNumber (value)E.164 "+989121234567"accepts 0912..., ۰۹۱۲..., 0098...National(): "0912 123 4567"Money (value)minor: int64, currency: CurrencyAdd, Sub, Times(Quantity), Allocateclosed: Money + Money = MoneyTotal (derived, not storedin the model)sum of unitPrice x quantitycached in a column for reports

در نمودار، فقط Order هویت (OrderId) و چرخهٔ عمر دارد؛ ShippingAddress، خط‌های OrderLine، Money، PhoneNumber و Quantity همه مقدارند و جایگزین می‌شوند، نه ویرایش. جمع (Total) مشتق است: جمع قیمت واحد ضرب در تعداد برای هر خط، و فقط برای گزارش‌ها در یک ستون cache می‌شود.

بحث OrderLine:

پرسشاگر «نه» -> مقداراگر «بله» -> Entity محلی
ممکن است دو خط SKU یکسان داشته باشند؟ادغامشان کنید؛ SKU خط را درون سفارشش مشخص می‌کندشناسهٔ خط لازم است
خط چرخهٔ عمر خودش را دارد (backorder، picked، returned)؟وضعیت روی Order یا در Fulfilment استخط گذار وضعیت دارد
contextهای دیگر به یک خط مشخص ارجاع می‌دهند؟به (شناسهٔ سفارش، SKU) ارجاع دهیدشناسهٔ پایدار خط لازم است
خط درجا ویرایش می‌شود (تغییر قیمت با audit)؟خط را جایگزین کنیدتغییرات همان خط را دنبال کنید
text
     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 OrderPlacedV1

راه درست: در Sales، OrderLine مقداری است که با SKU درون سفارشش شناخته می‌شود، همان‌طور که در کد این صفحه است. فصل Aggregates & Factories در کد Go خودش انتخاب کمی متفاوتی کرده: خط یک Entity درونی و unexported ریشهٔ Order است، باز هم با کلید SKU، که ریشه آن را درجا تغییر می‌دهد. هر دو خط را از بیرون دست‌نیافتنی و با SKU کلیددار نگه می‌دارند؛ فرق در «جایگزینی مقدار» (این صفحه) در برابر «تغییر از طریق ریشه» (آن صفحه) است. درون یک aggregate هر دو قابل‌دفاع‌اند؛ در هر codebase یکی را انتخاب کنید. چرخهٔ عمر هر قلم در اختیار Fulfilment است.

سازوکار ​

گزینه‌های نگاشت ذخیره‌سازی حیاتی ​

الگوی Embedded Value از Fowler "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". گزینهٔ چهارم، نوع تک‌ستونی است.

1. Embedded columns (Embedded Value)Money -> orders.total_minor bigint orders.total_currency char(3)+ queryable, indexable, CHECK per column- many columns for big values; NULL handlingLaravel: CastsAttributes::set returns an arrayGo: the repository maps fields to columns2. One JSON column (Serialized LOB)ShippingAddress -> orders.ship_to jsonb+ one read, one write; shape evolves in code- weak constraints, harder WHERE and joins- old rows keep old shapes: re-validate on readLaravel: Castable::castUsing(), AsArrayObjectGo: json.Marshal into []byte, or Valuer3. Dependent table (Dependent Mapping)OrderLine x N -> order_linesPRIMARY KEY (order_id, sku), no surrogate id+ normal SQL for reports, FK, CHECK- "replace the set" = DELETE + INSERT- an ORM may push you to give rows an id; that id is a database detail, not a model one4. Single-column typeOrderId -> uuid Email -> text / DOMAINOrderStatus -> text with CHECK (or enum type)+ simplest; database can share the rule (PostgreSQL CREATE DOMAIN ... CHECK)Go: sql.Scanner + driver.ValuerLaravel: enum cast, CastsAttributesIn every option the value object re-validates when it is read back: storage is outside the model's guarantee.

نمودار چهار گزینه را کنار هم می‌گذارد: ستون‌های جاسازی‌شده برای Money (قابل query و index، با CHECK برای هر ستون)، یک ستون JSON برای ShippingAddress (یک خواندن و یک نوشتن، ولی قید ضعیف و شکل‌های قدیمی)، جدول وابسته برای خط‌ها با کلید (order_id, sku) و بدون شناسهٔ جانشین، و نوع تک‌ستونی برای OrderId، Email و OrderStatus. در هر چهار حالت، مقدار هنگام خواندن دوباره اعتبارسنجی می‌شود.

گزینهمناسب برایquery و قیدهزینهٔ migrationLaravelGo
ستون‌های جاسازی‌شده (Embedded Value)Money، DateRange، نشانی کوچکSQL کامل، index، CHECKیک ستون برای هر فیلدCastsAttributes::set آرایه برمی‌گرداندrepository فیلدها را نگاشت می‌کند
ستون JSON / jsonb (Serialized LOB)نشانی، تنظیمات، snapshotعملگرهای jsonb؛ قید ضعیفردیف‌های قدیمی شکل قدیمی دارندCastable::castUsing، AsArrayObjectjson.Marshal به []byte
جدول وابسته (Dependent Mapping)مجموعه‌ای از مقدارهاSQL کامل؛ کلید بدون شناسهٔ جانشینجایگزینی مجموعه = delete + insertمدل دوم، نگاشت در repositoryquery دوم، نگاشت در repository
تک‌ستونشناسه، ایمیل، enumDomain/CHECKناچیزenum cast، cast سفارشیsql.Scanner + driver.Valuer

schema مثال جاری ما در PostgreSQL، با هر چهار گزینه:

sql
-- 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)
);

نوع domain در PostgreSQL قید مقدار در سطح پایگاه داده است: "A domain is essentially a data type with optional constraints (restrictions on the allowed set of values)." نمونهٔ کوتاه‌تر:

sql
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). هنگام بارگذاری، هر مقدار را از سازنده‌اش دوباره بسازید (تا ردیف‌های بد قدیمی با صدای بلند شکست بخورند)، ولی Entity را با یک تابع اختصاصی Rehydrate بسازید که حالت را بدون اجرای دوبارهٔ قاعده‌های ساخت می‌گذارد («سفارش باید با وضعیت draft شروع شود» دربارهٔ سفارش ارسال‌شدهٔ ذخیره‌شده صدق نمی‌کند). قرارداد Scanner در database/sql در Go: "An error should be returned if the value cannot be stored without loss of information"، و "Reference types such as []byte are only valid until the next call to Scan and should not be retained."

مقدارها در لبه: DTO، رویداد و پیام حیاتی ​

درون Bounded Context، مقدارها نوع‌اند. بیرون، یک زبان منتشرشده (Published language) هستند: یک شکل مستند JSON یا Protobuf. اشیای دامنه را مستقیم سریال نکنید؛ به DTO (شیء انتقال داده) نگاشت کنید، چون عوض‌کردن نام یک فیلد private نباید یک client را بشکند و مصرف‌کننده‌های زبان‌های دیگر نمی‌توانند سازندهٔ شما را اجرا کنند.

text
     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.
قاعدهچرا
پول به شکل عدد صحیح واحد خرد + کد ارز، و اختیاری یک رشتهٔ قالب‌بندی‌شدهعددهای JavaScript از نوع double در IEEE 754 هستند؛ float منحرف می‌شود
شناسه به شکل رشتهUUID از عدد صحیح 53 بیتی بزرگ‌تر است؛ client نباید روی شناسه حساب کند
enum به شکل رشتهٔ کوچک با فهرست مستنداضافه‌کردن یک case برای مصرف‌کننده تغییر قرارداد است
زمان به شکل لحظهٔ UTC در RFC 3339منطقهٔ زمانی مسئلهٔ نمایش است
رویدادها مقدارهای تغییرناپذیرندEvans: "Domain events are ordinarily immutable, as they are a record of something in the past."
نوع رویداد نسخه دارد (OrderPlacedV1)تغییر شکل باید صریح باشد (Message Design)

مستندات Laravel پیشنهاد می‌کند Value Objectهای روی مدل "implement the Illuminate\Contracts\Support\Arrayable and JsonSerializable interfaces" اگر مدل سریال می‌شود؛ برای آرایه‌های داخلی درست است، ولی قرارداد API باید یک JsonResource صریح باشد. سمت رویداد یکپارچه‌سازی (Integration event) در Domain Events vs Integration Events و انتشار مطمئن در Outbox آمده.

خطاهایی که می‌بینید ​

کجاپیام (عین متن)معنا
کامپایلر Goinvalid operation: a == b (struct containing []string cannot be compared)مقدار دارای فیلد slice مقایسه‌پذیر نیست
زمان اجرای Gopanic: runtime error: hash of unhashable type main.Tagsمقدار غیرقابل‌مقایسه از طریق any کلید شده
PHPError: Cannot modify readonly property Test::$prop (مثال راهنما)نوشتن روی ویژگی readonly
PHP 8.4Cannot modify private(set) property Manager::$calls from global scope (مثال راهنما)نوشتن با عبور از دید نامتقارن
enum در PHP"%s" is not a valid backing value for enum %s (php-src zend_enum.c، ValueError)from() با مقدار ناشناخته
cast سفارشی Laravel (مثال مستندات)The given value is not an Address instance.set چیزی غیر از VO گرفته
Go همین صفحهinvalid quantity: 60 not in 1..50یک عملیات invariant را شکسته
Go همین صفحهcurrency mismatch: EUR + USDبسته‌بودن با ارز پاسداری شده

Go ​

ماژول در docs/snippets/ddd/entities-value-objects/go است و فقط از کتابخانهٔ استاندارد استفاده می‌کند؛ gofmt -l . خالی است و go vet ./... و go test ./... پاس می‌شوند (خروجی در آزمایشگاه).

پیش از: همه‌جا نوع ابتدایی ​

کامپایل می‌شود، اجرا می‌شود و همهٔ باگ‌های این صفحه را راه می‌دهد:

go
// 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 Objectها ​

Currency و Money: واحد خرد صحیح، توان‌های ISO 4217، Add بسته، Times و PercentOf نیمه‌بسته، Allocate که هرگز یک واحد را گم نمی‌کند، و parse بدون float64:

go
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 }
go
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 و Percentage (با basis point، تا ۱۲٫۵٪ دقیق باشد):

go
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) }
go
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 و PhoneNumber موبایل ایران (شکل متعارف E.164؛ نگاشت صریح ارقام فارسی و عربی-هندی؛ کد کشور ۹۸ و پیشوند ملی ۰ طبق metadata کتابخانهٔ libphonenumber گوگل، که شمارهٔ ملی موبایل را ۱۰ رقمی و شروع‌شونده با ۹ می‌داند):

go
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 }
go
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 همهٔ مشکل‌ها را جمع می‌کند؛ DateRange در فیلدهایش time.Time نگه نمی‌دارد تا == امن باشد:

go
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 }
go
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 طبق RFC 9562)، CustomerID و enum OrderStatus:

go
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 }
go
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 }
go
// 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")
)

Entity ​

OrderLine مقدار است؛ Order Entity است: receiver اشاره‌گری، حالت unexported، متدهای نیت‌نما، SameAs برای برابری هویتی، Lines() که کپی برمی‌گرداند و Rehydrate برای repository:

go
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
}
go
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}
}

ماندگاری و لبه ​

Scanner/Valuer برای مقدارهای تک‌ستونی، repository برای ستون‌های جاسازی‌شده، JSON و جدول وابسته (با چک خوش‌بینانهٔ version)، و DTO برای HTTP و رویدادها:

go
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
}
go
// 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, &currencyCode, &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)
}
go
// 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()})
}

تست‌ها ​

برابری، بسته‌بودن، تست مبتنی بر ویژگی (Property-based) برای Allocate روی ۱۰٬۰۰۰ حالت تصادفی با seed ثابت (math/rand/v2)، تست fuzz که idempotent بودن نرمال‌سازی تلفن را چک می‌کند، و تست‌های هویت Entity:

go
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)
	}
}
go
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")
	}
}
go
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)
	}
}
go
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)
	}
}

نگاه Go ​

قابلیت Goنقش برای Entity و مقدارنکته
فیلدهای unexported + NewXتنها در ورود به یک مقدارکد همان package هنوز می‌تواند Money{} بسازد؛ package را کوچک نگه دارید
receiver مقداریمتدها کپی می‌گیرند؛ with-er مجانی استreceiver اشاره‌گری فقط روی Entity
struct مقایسه‌پذیر== و کلید map برای مقدار"Struct types are comparable if all their field types are comparable" (spec)
قید comparableمجموعه یا cache generic از مقدارهاinterfaceی که نوع غیرقابل‌مقایسه دارد روی == panic می‌کند
genericsMoney[C Currency] ممکن است ولی به‌ندرت می‌ارزدفیلد Currency در زمان اجرا ساده‌تر و سریال‌پذیرتر است
database/sqlScanner، driver.Valuerیک ستون برای هر مقدار؛ مقدار چندستونی در repository
encoding/jsonMarshaler/Unmarshalerدر لبه DTO را به marshaler روی نوع دامنه ترجیح دهید
fuzz در testing، testing/quickتست ویژگی و fuzztesting/quick "is frozen and is not accepting new features"؛ حلقه با math/rand/v2 و seed یا fuzz بومی

Laravel ​

Laravel 13 روی PHP 8.4 (final readonly class، دید نامتقارن، ثابت‌های کلاس تایپ‌دار). فایل‌ها زیر docs/snippets/ddd/entities-value-objects/php هستند؛ PHP روی ماشین نویسنده نصب نیست، پس کد بازبینی شده، اجرا نشده.

پیش از: مدل Eloquent همان Entity است و همه‌جا نوع ابتدایی ​

php
<?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 Objectها ​

php
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 قرارداد Castable لاراول را پیاده می‌کند تا مدل بتواند بنویسد 'ship_to' => ShippingAddress::class. این یک interface فریم‌ورک را روی کلاس دامنه می‌گذارد؛ اگر می‌خواهید دامنه از Illuminate پاک بماند، Castable را بردارید و روی مدل 'ship_to' => AsShippingAddress::class بنویسید.

php
<?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
<?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;
    }
}

Entity ​

public private(set) (دید نامتقارن PHP 8.4) خواندن عمومی و نوشتن خصوصی را بدون getter می‌دهد؛ setter وجود ندارد:

php
<?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
<?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;
    }
}

ماندگاری: castها، مدل‌های رکورد و یک repository ​

AsMoney یک مقدار جاسازی‌شده روی دو ستون است (پارامترهای cast "passed to the constructor" می‌شوند)؛ AsShippingAddress به یک ستون JSON سریال می‌کند؛ enum castها Currency و OrderStatus را می‌گردانند:

php
<?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
<?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
<?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
<?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
<?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);
    }
}

لبهٔ API ​

php
<?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),
        ];
    }
}

تست‌ها ​

php
<?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
<?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'));
    }
}

نگاه Laravel ​

قابلیت Laravelنقشهشدار
CastsAttributes (get/set)نگاشت یک مقدار به یک یا چند ستونجملهٔ مستندات "any changes made to the value object will automatically be synced back to the model" مقدار تغییرپذیر را فرض می‌کند؛ با مقدار readonly نمونهٔ تازه بگذارید
Castable::castUsingمقدار caster خودش را نام می‌بردinterface فریم‌ورک روی کلاس دامنه
withoutObjectCachingخاموش‌کردن cache نمونه برای هر ویژگیبرای مقدار تغییرناپذیر بی‌ضرر است
CastsInboundAttributesتبدیل فقط هنگام نوشتن (hash)Value Object نیست
SerializesCastableAttributesکنترل toArray/toJson مقدار cast‌شدهبرای API یک JsonResource صریح بهتر است
ComparesCastableAttributesتصمیم اینکه مقدار cast‌شده «dirty» است یا نهبرای مقایسهٔ مقدار از equals() استفاده کنید
enum cast، AsEnumCollectionenumهای پشتیبانی‌شده به‌عنوان ویژگیمقدار ناشناخته ValueError می‌دهد
Attribute::make(get:, set:)accessor که از چند ستون یک مقدار می‌سازد ($attributes)برای مدل‌های خواندنی خوب است
HasUuids، Str::uuid7()شناسهٔ UUIDv7 تولیدشده در برنامه$incrementing = false و $keyType = 'string'
$model->is($other)برابری Entity برای مدل Eloquentکلید، جدول و اتصال را مقایسه می‌کند
JsonResourceDTO در لبهقرارداد همین است؛ مدل را مستقیم برنگردانید

حل مسئله‌های کلاسیک ​

مسئلهراه‌حلچطورمزیتهزینه / محدودیت
Value Object تغییرپذیرتغییرناپذیرش کنیدفیلد unexported / readonly؛ with-erبدون باگ aliasingتخصیص حافظهٔ بیشتر (برای مقدار کوچک ناچیز)
Entity با setter عمومیمتدهای نیت‌نماPlace()، ShipTo() به‌جای setStatus()invariant در یک جاکد نگاشت برای ماندگاری
Value Object با شناسهشناسه را بردارید؛ کلید با مالک + ویژگی‌هاجدول وابسته (order_id, sku)مدل صادق، برابری ساده‌ترORM ممکن است کلید جانشین بخواهد؛ آن را بیرون دامنه نگه دارید
مدل Eloquent همه‌جا به‌جای Entityجدا کردن رکورد از Entity جایی که منطق غنی استrepository، OrderRecord را به Order نگاشت می‌کنددامنه بدون DB تست‌پذیردو کلاس برای هر مفهوم
float برای پولواحد خرد صحیحMoney{minor int64, currency}جمع دقیقکد قالب‌بندی و parse
وسواس به نوع ابتداییمقدار کامل را کم‌کم وارد کنیدPhoneNumber، Email، OrderIdبررسی نوع، یک نقطهٔ اعتبارسنجینوع‌های کوچک بیشتر

Value Object تغییرپذیر ​

نشانه: متدی مثل Money::setAmount() یا $address->city = .... درمان: setter را بردارید، withX() اضافه کنید که نمونهٔ تازه برمی‌گرداند، و مقدار را روی Entity با متدی جایگزین کنید که قاعدهٔ چرخهٔ عمر را چک می‌کند (Order::shipTo). در Go، receiverهای اشاره‌گری روی نوع مقداری را به receiver مقداری تبدیل کنید.

Entity با setter عمومی ​

نشانه: order.SetStatus("dispatched") از هر جا قابل فراخوانی است، پس قاعدهٔ «فقط سفارش پرداخت‌شده ارسال می‌شود» در controllerها زندگی می‌کند. درمان: یک متد برای هر عملیات کسب‌وکار (MarkDispatched)، حالت unexported یا private(set)، و مسیر Rehydrate فقط برای repository. Anemic vs Rich را ببینید؛ مدل کم‌خون (Anemic domain model) همین‌جا شروع می‌شود.

Value Object با شناسه ​

نشانه: order_lines.id وجود دارد و کد خط‌ها را با آن مقایسه می‌کند، یا جدول دیگری به شناسهٔ خط اشاره می‌کند. درمان: اگر هیچ چیز بیرون از سفارش به خط ارجاع نمی‌دهد، شناسه را از مدل بردارید (جدول می‌تواند برای ORM یک کلید جانشین نگه دارد) و خط را با (order_id, sku) بشناسید. اگر چیزی ارجاع می‌دهد، Entity محلی است: صادقانه مدلش کنید.

مدل Eloquent به‌عنوان Entity، و کی قابل‌قبول است ​

استفاده از مدل Eloquent به‌عنوان Entity وقتی دامنه شبیه CRUD است مشکلی ندارد (زیردامنهٔ Supporting یا Generic، Domains & Subdomains): پنل مدیریت، تنظیمات، ویرایش کاتالوگ. حتی آنجا Value Objectها را با cast روی مدل بگذارید ('total' => AsMoney::class.':total'، enum cast). رکورد و Entity را وقتی جدا کنید که دامنهٔ Core قاعده‌هایی دارد که باید بدون پایگاه داده تست شوند، وقتی چند نقطهٔ ورود (HTTP، صف، import) باید invariantها را شریک باشند، یا وقتی مدل نباید save()، fill() و mass assignment را در اختیار فراخواننده بگذارد.

انتخاب ​

وضعیتپیشنهادروش تکمیلیدلیل
هر چیزی با ارزمقدار Money با واحد خرد صحیحAllocate، قاعدهٔ گردکردن صریحfloat سنت گم می‌کند؛ ارزها نباید قاطی شوند
چیزی که در حالت‌های مختلف دنبال می‌شودEntity با شناسهٔ تایپ‌دارRehydrate، ستون versionهویت و چرخهٔ عمر
قالب شناسه، یک پایگاه دادهUUIDv7 یا bigint identityOrderId تایپ‌داردرج مرتب؛ با UUIDv7 پیش از ماندگاری ساخته می‌شود
شناسه‌ای که مشتری می‌بیندشمارهٔ نمایشی جداValue Object OrderNumberقالب را بدون دست‌زدن به کلید عوض کنید
اطلاعات تماسEmail، PhoneNumberشکل متعارف هنگام ساختحذف تکرار، برابری، API شرکت حمل
مجموعه‌ای از اجزای کوچکمقدارها در جدول وابستهجایگزینی مجموعه هنگام ذخیرهبدون شناسهٔ ساختگی در مدل
snapshot از دادهٔ context دیگرمقدار (مثل نشانی صورت‌حساب هنگام صدور)ستون JSONنباید با تغییر منبع عوض شود
مجموعهٔ بستهٔ حالت‌هامقدار enumمتد برای قاعده‌هاparse و قاعده در یک جا
context پشتیبان پر از CRUDمدل Eloquent به‌عنوان Entitycast برای مقدارهاکد نگاشت کمتر جایی که قاعده کم است
دامنهٔ Core با قاعده‌های غنیEntity دامنهٔ جدا + مدل رکوردنگاشت در repositoryقاعده‌های تست‌پذیر و مستقل از فریم‌ورک

در معماری: از یک پروسه تا سیستم توزیع‌شده ​

همان Order و مقدارهایش در هر مرحله. مقدارها خوب سفر می‌کنند؛ شناسه‌ها وقتی داده از یک پایگاه داده بیرون می‌رود باید سراسری یکتا باشند.

Monolith (یکپارچه): یک پروسه، یک پایگاه داده ​

چطور دیده می‌شود: Value Objectها در ماژول Sales زندگی می‌کنند و درون آن آزادانه import می‌شوند؛ Order با خط‌هایش در یک تراکنش ذخیره می‌شود.

مثال (ساده): یک اپ Laravel تکی: OrderRecord با AsMoney و enum cast، enum OrderStatus، و controllerهایی که از OrderResource استفاده می‌کنند. هنوز Entity دامنهٔ جدا نداریم؛ همین مقدارها باگ‌های float و غلط تایپی را حذف می‌کنند.

مثال (شبیه production): همان اپ بعد از شش ماه: قاعده‌های checkout بزرگ شدند، پس App\Domain\Sales\Order با EloquentOrderRepository اضافه شد؛ OrderRecord حالا فقط در repository و پنل مدیریت به کار می‌رود.

Modular monolith و چند پایگاه داده ​

چطور دیده می‌شود: هر ماژول صاحب مقدارهای خودش است. اشتراک یک package Money میان Sales و Billing یک هستهٔ مشترک (Shared kernel) آگاهانه است (Context Maps)؛ اشتراک Order نه. ارجاع میان ماژول‌ها با شناسه است (OrderId به شکل رشته در مرز ماژول).

text
     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.orders

Microservices (میکروسرویس): مقدارها قرارداد می‌شوند ​

آنچه می‌ماند: قاعده‌های یک مقدار (واحد خرد، کد ISO، E.164) به شکل زبان منتشرشدهٔ مستند؛ شناسه به شکل رشته؛ تغییرناپذیری رویدادها. آنچه نمی‌ماند: خود نوع. هر سرویس پیاده‌سازی Money خودش را دارد؛ کتابخانهٔ مشترک مقدارهای دامنه میان سرویس‌ها deployها را به هم گره می‌زند (Service Boundaries).

text
     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 it

دادهٔ توزیع‌شده: replica، cache و چندمنطقه‌ای ​

جایی که مقدار و شناسه به توزیع می‌رسندچه می‌شکندپاسخ طراحی
شناسه‌هایی که در چند گره یا منطقه ساخته می‌شوندبرخورد، صفحه‌های داغ indexUUIDv7/ULID یا Snowflake (تولید شناسه)
مقدارهای سریال‌شده در cache (Redis)شکل قدیمی بعد از deploy؛ قالب floatکلید cache نسخه‌دار؛ شکل DTO، نه serialize() شیء
replicaهای خواندنینسخهٔ کهنهٔ Entityستون version، read-your-writes برای مالک
زمان میان منطقه‌ها== روی time.Time، شگفتی‌های DSTلحظهٔ UTC ذخیره کنید؛ منطقه (Asia/Tehran) فقط هنگام نمایش
پول با ارزهای مختلف در گزارشجمع یورو با ریالگروه‌بندی با ارز؛ تبدیل با نرخ تاریخ‌دار که خودش یک مقدار است
کلیدهای متنی از clientهای مختلفحروف و ارقام فارسی در برابر عربیپیش از ذخیره یا index، در سازندهٔ مقدار متعارف کنید

مسیر مقیاس (Scaling path): ۱×، ۱۰×، ۱۰۰× ​

مقیاسEntity و مقدارروش‌ها
1× (یک تیم)مقدارها روی مدل‌های Eloquent با cast؛ Order می‌تواند همان مدل باشدپول با واحد خرد، enum، شناسهٔ تایپ‌دار
10× (چند تیم، ماژول)Entity دامنهٔ جدا از رکورد در ماژول‌های Core؛ package مقدار برای هر ماژول؛ هستهٔ مشترک کوچکتست ویژگی برای مقدارها، contract test برای DTOها، شناسهٔ UUIDv7
100× (سرویس‌های زیاد)هر سرویس صاحب نوع‌های مقداری خودش؛ زبان منتشرشده برای مقدارها در رویدادهاschema registry یا JSON Schema برای شکل رویداد، تولید شناسه بدون هماهنگی، قاعده‌های متعارف‌سازی مستند برای هر فیلد

آزمایشگاه: مقدارها را بسازید، بشکنید و ذخیره کنید ​

همه‌چیز بدون شبکه با Go نصب‌شده اجرا می‌شود (Go 1.24 یا بالاتر).

آماده‌سازی.

bash
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]

آزمایش ۱: انحراف float در برابر واحد خرد. در یک پوشهٔ موقت یک main.go آزمایشی بنویسید:

go
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 not

بعد go test ./sales -run TestParseMoneyNeverUsesFloat -v را اجرا کنید و ببینید 0.30 به 30 واحد خرد parse می‌شود.

آزمایش ۲: مقایسه‌پذیری. به یک struct فیلد slice اضافه کنید و دو مقدار را مقایسه کنید: کامپایلر می‌گوید invalid operation: a == b (struct containing []string cannot be compared). همان struct را در یک map[any]int بگذارید: کامپایل می‌شود و با hash of unhashable type panic می‌کند. به همین دلیل Order (که slice دارد) با == مقایسه نمی‌شود و Money می‌شود.

آزمایش ۳: ویژگی تخصیص. حلقهٔ باقی‌مانده را از Allocate پاک کنید و go test ./sales -run Allocate -v را اجرا کنید. تست ویژگی اولین مبلغ و نسبت‌هایی را گزارش می‌کند که جمع بخش‌هایشان درست درنمی‌آید، و seed ثابت شکست را تکرارپذیر می‌کند.

آزمایش ۴: fuzz روی parser تلفن.

bash
go test ./sales -run XXX -fuzz FuzzIranianMobile -fuzztime 10s
# fuzz: elapsed: ..., execs: ..., new interesting: ...
# PASS

حالا شاخهٔ ارقام فارسی را از phone.go حذف کنید: TestIranianMobileAcceptsEveryCommonSpelling روی "۰۹۱۲۱۲۳۴۵۶۷" شکست می‌خورد.

آزمایش ۵: هویت در برابر مقدار. در order_test.go، تست TestEntityEqualityIsByIdentity یک *Order دوم با همان شناسه و خط‌های متفاوت می‌سازد (SameAs درست است) و یک سفارش تازه با ویژگی‌های برابر (SameAs نادرست است). SameAs را طوری عوض کنید که جمع‌ها را مقایسه کند و ببینید کدام تست می‌شکند.

آزمایش ۶ (PostgreSQL). store/schema.sql را در یک پایگاه دادهٔ آزمایشی بارگذاری کنید، ردیفی با quantity = 0 در order_lines درج کنید و نقض CHECK را بخوانید (SQLSTATE 23514، check_violation)؛ currency = 'eur' را درج کنید و ببینید چک domain ردش می‌کند. پایگاه داده آخرین خط دفاع است و Value Object اولین.

بدفهمی‌های رایج ​

باورواقعیت
Entity = جدول، Value Object = ستوناصطلاح‌های DDD دربارهٔ هویت و برابری‌اند؛ ذخیره‌سازی انتخاب جداگانه‌ای است
Value Object همان DTO استکاربرد قدیمی J2EE؛ مقدار DDD رفتار و invariant دارد، DTO ندارد
چیزهایی که عوض می‌شوند Entityاندنگه‌دارنده با جایگزینی مقدار عوض می‌شود؛ پیوستگی هویت تصمیم می‌گیرد
هر Entity شناسهٔ auto-increment می‌خواهدشناسه می‌تواند از کاربر، برنامه (UUIDv7)، پایگاه داده یا context دیگر بیاید
readonly مقدار PHP را کاملاً تغییرناپذیر می‌کنداشیای درون ویژگی readonly هنوز تغییرپذیرند ("interior mutability")
struct در Go تغییرناپذیر است چون کپی می‌شودفیلدهای exported و receiver اشاره‌گری تغییر را ممکن می‌کنند؛ slice درونی آرایه را شریک است
float اشکالی ندارد اگر آخر کار گرد کنیدخطا پیش از گردکردن جمع می‌شود؛ واحد خرد صحیح به کار ببرید
نرمال‌سازی یونیکد متن فارسی را قابل‌مقایسه می‌کندNFC/NFKC «ي» و «ی» و ارقام فارسی را جدا نگه می‌دارند؛ صریح یکسان کنید
اعتبارسنجی در controller کافی استصف، import و تست از controller رد نمی‌شوند؛ invariant جایش سازنده است
مقدارها باید مستقیم به API سریال شوندبه DTO نگاشت کنید؛ شکل JSON قرارداد است
استفاده از مدل Eloquent به‌عنوان Entity همیشه غلط استبرای contextهای پشتیبان پر از CRUD درست است؛ cast مقدار اضافه کنید
خط سفارش باید Entity باشد چون جدول داردخطی که با SKU درون سفارش شناخته می‌شود مقدار است؛ جدول جزئیات ذخیره‌سازی است

چکیده ​

موضوعبه خاطر بسپارید
Entityهویت در طول زمان؛ برابری با شناسه؛ چرخهٔ عمر؛ بدون setter عمومی
Value Objectفقط ویژگی‌ها؛ تغییرناپذیر؛ برابری با مقدار؛ جایگزین کنید، ویرایش نکنید
پرسش اصلی«اگر با یکی کاملاً یکسان عوضش کنم، کسب‌وکار اهمیت می‌دهد؟»
شناسهتایپ‌دار (OrderId)؛ پایدار؛ در صورت امکان پیش از ماندگاری ساخته شود (UUIDv7)
Invariantدر سازنده؛ همیشه‌معتبر؛ برای فرم خطاها را جمع کنید
تغییرناپذیریGo: فیلد unexported + receiver مقداری؛ PHP: final readonly class + with-er
بسته‌بودنMoney + Money = Money؛ تخصیص بدهید، تقسیم نکنید
پولواحد خرد صحیح + ارز ISO 4217؛ توان برای هر ارز
برابریشکل متعارف هنگام ساخت؛ مراقب float، time.Time و ارقام فارسی
enumenum پشتیبانی‌شده با متد در PHP؛ ثابت تایپ‌دار از 1 با String() در Go
ماندگاریستون جاسازی‌شده، ستون JSON، جدول وابسته، تک‌ستون؛ هنگام خواندن دوباره اعتبارسنجی
لبهDTO و رویداد نسخه‌دار؛ شناسه به شکل رشته، مبلغ به شکل عدد صحیح
تستبرابری، invariant، تست ویژگی برای حساب، fuzz برای parser
Eloquentcast برای مقدارها؛ Entity جدا فقط جایی که قاعده غنی است

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — کدام پرسش تکی بین Entity و مقدار تصمیم می‌گیرد و چه کسی جوابش را می‌دهد؟ حیاتی ​

پاسخ

پاسخ: «اگر این نمونه با نمونهٔ دیگری با ویژگی‌های کاملاً یکسان عوض شود، کسب‌وکار اهمیت می‌دهد؟» متخصص دامنه جواب می‌دهد، برای هر Bounded Context جدا. پرسش هویت را ببینید.

۲ — جملهٔ Evans دربارهٔ اینکه مدل یک Entity باید چه چیزی را تعریف کند چیست؟ تکمیلی ​

پاسخ

پاسخ: "The model must define what it means to be the same thing." Entity را ببینید.

۳ — چرا UUIDv7 تولیدشده در برنامه اغلب برای Order از شناسهٔ auto-increment بهتر است؟ مهم ​

پاسخ

پاسخ: پیش از INSERT وجود دارد، پس می‌تواند در رویداد outbox برود و در همان تراکنش کلید پایدار برای retry باشد؛ مرتب زمانی است و درج در B-tree محلی می‌ماند؛ حجم سفارش‌ها را لو نمی‌دهد. هزینه: ۱۶ بایت و افشای زمان ساخت. انتخاب و تولید هویت را ببینید.

۴ — روش‌های PHP 8.4 و Go برای تغییرناپذیر کردن یک مقدار را نام ببرید. مهم ​

پاسخ

پاسخ: PHP: final readonly class، سازندهٔ private با سازنده‌های نام‌دار، with-er که new self(...) برمی‌گرداند (یا clone($this, [...]) در 8.5). Go: فیلد unexported، سازندهٔ NewX، receiver مقداری که مقدار تازه برمی‌گرداند، کپی دفاعی slice. تغییرناپذیری را ببینید.

۵ — چرا Money متد Allocate دارد ولی Divide ندارد؟ مهم ​

پاسخ

پاسخ: تقسیم روی پول بسته نیست (10.00 / 3 مبلغ پولی نیست) و بی‌صدا واحد خرد گم می‌کند؛ تخصیص بخش‌هایی برمی‌گرداند که جمعشان دقیقاً کل است. بسته‌بودن عملیات را ببینید.

۶ — دو دلیل بیاورید که چرا مقدار Go دارای time.Time ممکن است برای یک لحظهٔ یکسان نابرابر دربیاید. تکمیلی ​

پاسخ

پاسخ: == علاوه بر لحظه، Location و خوانش ساعت monotonic را هم مقایسه می‌کند. UTC یا فیلدهای تاریخ مدنی ذخیره کنید، یا با Equal مقایسه کنید. تله‌های برابری را ببینید.

۷ — آیا NFKC یونیکد «۰۹۱۲» را با «0912» برابر می‌کند؟ تکمیلی ​

پاسخ

پاسخ: نه. ارقام فارسی (U+06F0 تا U+06F9) با NFC و NFKC تغییر نمی‌کنند؛ آن‌ها را در سازندهٔ مقدار صریح نگاشت کنید، همان کاری که PhoneNumber می‌کند. تله‌های برابری را ببینید.

۸ — OrderLine کی مقدار است و کی Entity؟ حیاتی ​

پاسخ

پاسخ: مقدار است وقتی با SKU درون سفارشش شناخته می‌شود، یکجا جایگزین می‌شود و چرخهٔ عمر خودش را ندارد (Sales). Entity محلی است وقتی هر قلم جداگانه در picking، backorder و مرجوعی دنبال می‌شود (ShipmentItem در Fulfilment). بحث OrderLine را ببینید.

۹ — چهار گزینهٔ ذخیره‌سازی Value Object و یک ضعف هر کدام را نام ببرید. مهم ​

پاسخ

پاسخ: ستون‌های جاسازی‌شده (ستون زیاد برای مقدار بزرگ)، ستون JSON (قید ضعیف، شکل‌های قدیمی)، جدول وابسته (جایگزینی = delete + insert)، تک‌ستون (فقط برای مقدار تک‌فیلدی). نگاشت ذخیره‌سازی را ببینید.

۱۰ — چرا API نباید سریال‌سازی درونی شیء Money دامنه را برگرداند؟ مهم ​

پاسخ

پاسخ: شکل JSON قرارداد است؛ تغییر نام یک فیلد private clientها را می‌شکند و زبان‌های دیگر نمی‌توانند سازندهٔ شما را اجرا کنند. به DTO با amount_minor، currency و اختیاری formatted نگاشت کنید. مقدارها در لبه را ببینید.

۱۱ — کی استفاده از مدل Eloquent به‌عنوان Entity قابل‌قبول است؟ مهم ​

پاسخ

پاسخ: در contextهای پشتیبان یا عمومی پر از CRUD با قاعده‌های کم؛ حتی آنجا Value Objectها را با cast رویش بگذارید. وقتی قاعده‌های Core باید بدون پایگاه داده تست شوند یا میان چند نقطهٔ ورود شریک باشند، جدا کنید. Eloquent به‌عنوان Entity را ببینید.

واژه‌نامه ​

اصطلاحمعنا
موجودیت (Entity)شیئی که با رشته‌ای از هویت در طول زمان تعریف می‌شود؛ برابری با شناسه (Evans)
شیء ارجاعی (Reference object)اصطلاح عمومی Fowler برای اشیایی که با هویت مقایسه می‌شوند؛ Entity یکی از آن‌هاست
شیء مقداری (Value object)شیئی که فقط ترکیب ویژگی‌هایش مهم است؛ تغییرناپذیر، برابری با مقدار
هویت (Identity)آنچه یک Entity را در طول تغییرات «همان یکی» نگه می‌دارد
چرخهٔ عمر (Lifecycle)حالت‌هایی که Entity از آن‌ها می‌گذرد (draft، placed، paid، dispatched)
کلید طبیعی (Natural key)شناسه‌ای از خود دامنه (ISBN، IBAN)
کلید / هویت جانشین (Surrogate key / identity)شناسه‌ای که سیستم برای خودش می‌سازد، اغلب کنار شناسهٔ دامنه
شناسهٔ تایپ‌دار (Typed id)نوع مقداری که شناسه را می‌پیچد (OrderId) تا شناسه‌های نوع‌های مختلف قاطی نشوند
UUIDv7UUID طبق RFC 9562 با پیشوند 48 بیتی میلی‌ثانیهٔ Unix؛ مرتب زمانی
ULIDشناسهٔ 128 بیتی قابل‌مرتب‌سازی با پیشوند زمانی (صفحهٔ تولید شناسه)
Invariantقاعده‌ای که همیشه باید برای یک شیء برقرار باشد
همیشه‌معتبر / خوداعتبارسنج (Always-valid / self-validating)شیئی که نمی‌شود آن را در حالت نامعتبر ساخت
شکست سریع (Fail fast)رد در اولین قاعدهٔ شکسته
الگوی Notificationجمع‌کردن همهٔ مشکل‌های اعتبارسنجی و گزارش یکجا (Fowler)
تغییرناپذیری (Immutability)هیچ عملیاتی بعد از ساخت حالت قابل‌مشاهده را عوض نمی‌کند
باگ aliasing (Aliasing bug)تغییری از یک ارجاع که ناخواسته از ارجاع دیگر دیده می‌شود
with-erمتدی که کپی‌ای با یک ویژگی تغییرکرده برمی‌گرداند (withLine2)
تابع بی‌اثر جانبی (Side-effect-free function)عملیاتی که نتیجه برمی‌گرداند بدون تغییر حالت قابل‌مشاهده (Evans)
جداسازی فرمان و پرسش (Command-query separation)فرمان حالت را عوض می‌کند و دادهٔ دامنه برنمی‌گرداند؛ پرسش فقط برمی‌گرداند
بسته‌بودن عملیات (Closure of operations)عملیاتی که نوع آرگومان و خروجی‌اش همان نوع پیاده‌کننده است (Evans)
تخصیص (Allocation)تقسیم پول با نسبت‌ها طوری که جمع بخش‌ها دقیقاً کل باشد
واحد خرد (Minor unit)کوچک‌ترین واحد ارز (سنت)؛ ISO 4217 توانش را برای هر ارز می‌دهد
ISO 4217فهرست استاندارد کد ارزها و توان واحد خرد
basis pointیک‌صدم درصد؛ 12.5% = 1250 bp
مقدار کامل (Whole value)نوعی که یک کمیت کامل دامنه را نشان می‌دهد نه نوع ابتدایی خام (Cunningham)
وسواس به نوع ابتدایی (Primitive obsession)استفاده از رشته و عدد جایی که نوع دامنه لازم است
مرزهای مفهومی (Conceptual contours)بریدن نوع‌ها و عملیات در امتداد تقسیم‌های طبیعی دامنه (Evans)
کلِ مفهومی (Conceptual whole)ویژگی‌هایی که فقط با هم معنا دارند (Vernon)
نوع استاندارد (Standard Type)مقدار پرکاربرد مشترک مثل ارز یا کد کشور (Vernon)
شکل متعارف (Canonical form)تنها نمایش نرمال‌شده‌ای که مقدار ذخیره و مقایسه می‌کند
E.164قالب بین‌المللی شمارهٔ تلفن، مثل +989121234567
نرمال‌سازی یونیکد (NFC، NFKC)شکل‌هایی که به رشته‌های هم‌ارز یک نمایش دودویی می‌دهند (UAX 15)
خوانش ساعت monotonicبخشی از time.Time در Go برای اندازه‌گیری مدت؛ روی == اثر دارد
enum پشتیبانی‌شده (Backed enum)enum در PHP که caseهایش مقدار scalar دارند؛ from / tryFrom
comparable (Go)نوع‌هایی که با == و به‌عنوان کلید map قابل‌استفاده‌اند
Embedded Valueنگاشت فیلدهای یک مقدار به ستون‌های جدول مالک (Fowler)
Serialized LOBذخیرهٔ یک گراف شیء در یک ستون، مثلاً JSON (Fowler)
Dependent Mappingmapper مالک، اشیای فرزند را هم نگاشت می‌کند (Fowler)
بازسازی (Rehydration)ساختن دوبارهٔ Entity از ذخیره‌سازی بدون اجرای قاعده‌های ساخت
CastsAttributesinterface در Laravel با get/set برای نگاشت ویژگی به مقدار
Castable / castUsinginterface در Laravel که به مقدار اجازه می‌دهد caster خودش را نام ببرد
sql.Scanner / driver.Valuerinterfaceهای Go برای خواندن یک ستون به نوع و نوشتن دوباره‌اش
DTOشیء انتقال داده: شکلی برای عبور از مرز، بدون رفتار
زبان منتشرشده (Published language)قالب مشترک مستند میان contextها
رویداد یکپارچه‌سازی (Integration event)رویدادی که به زبان منتشرشده برای contextهای دیگر منتشر می‌شود
تست مبتنی بر ویژگی (Property-based test)تستی که یک قاعده را روی ورودی‌های تولیدشدهٔ زیاد چک می‌کند
fuzzingتولید خودکار ورودی با راهنمایی coverage برای یافتن شکست (fuzz بومی Go)
دید نامتقارن (Asymmetric visibility)public private(set) در PHP 8.4: دامنهٔ خواندن و نوشتن متفاوت
property hookshookهای get/set روی ویژگی در PHP 8.4؛ با readonly ناسازگار
CREATE DOMAINنوع دادهٔ PostgreSQL با قید
مدل کم‌خون (Anemic domain model)اشیایی با داده ولی بدون رفتار (فصل همسایه)

منابع ​

ساخته‌شده توسط Morteza Negahi