Skip to content

Repositories: مجموعه‌ای از Aggregateها، نه دروازهٔ جدول ​

"For each type of aggregate that needs global access, create a service that can provide the illusion of an in-memory collection of all objects of that aggregate's root type." — Eric Evans, Domain-Driven Design Reference (2015), Repositories

خلاصه (Summary): «مخزن (Repository)» دری است که برنامه از آن، «اگریگیت (Aggregate)»های کامل را می‌خواند و ذخیره می‌کند؛ برای هر ریشهٔ اگریگیت یکی، به زبان دامنه؛ پایگاه داده را پنهان می‌کند، هیچ‌وقت تراکنش را commit نمی‌کند و به پرسش‌های گزارش‌گیری جواب نمی‌دهد. تمرکز (Focus): تعریف Evans و Fowler، رابط «مجموعه‌محور (Collection-oriented)» در برابر «ذخیره‌محور (Persistence-oriented)»، آنچه در repository می‌آید و آنچه به «مدل خواندنی (Read Model)» می‌رود، الگوی «مشخصه (Specification)» و محدودیت‌هایش، تراکنش و «واحد کار (Unit of Work)»، همزمانی خوش‌بینانه در Save، «بازسازی (Reconstitution)»، سه راهبرد Laravel، Go با pgx و sqlc، fake و contract test، کش، انتشار رویداد و ضدالگوها. هدف یادگیری (Learning goal): برای یک aggregate یک OrderRepository در Go و Laravel بنویسید، دو پیاده‌سازی (حافظه و Postgres) که یک contract test مشترک را پاس کنند، تراکنش را در سرویس برنامه ببندید، با ستون version «به‌روزرسانی گمشده (Lost Update)» را پیدا کنید و repositoryای را که به DAO تبدیل شده تشخیص دهید.

این فصل در گروه DD 02 (طراحی تاکتیکی) است و فرض می‌کند Aggregates & Factories و Entities & Value Objects را خوانده‌اید. فقط یک پرسش را جواب می‌دهد: دامنه چطور یک aggregate را پس بگیرد و برای ذخیره تحویل دهد، بی‌آنکه چیزی از SQL بداند؟ همسایه‌ها بقیه را دارند: بحث کلی ماندگاری (Active Record در برابر Data Mapper، Unit of Work، Identity Map) در Data Persistence Design؛ سرویس‌هایی که repository را صدا می‌زنند در Domain, Application & Infrastructure Services؛ رویدادهای ذخیره‌شده در Domain Events vs Integration Events و Outbox Pattern؛ سمت پرس‌وجو در Data Patterns؛ ستون version در Optimistic vs Pessimistic Locking.

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

دنبال چه هستیدبروید به
کل فصل در چهار جدولهمه‌چیز در یک دقیقه
چرا اصلاً یک در لازم استچرا repository وجود دارد
Evans و Fowler و Vernonاز کجا آمده
یکی برای هر ریشه، aggregate کاملRepository چیست
Add/Remove در برابر Save، کدام به Go و PHP می‌خوردمجموعه‌محور در برابر ذخیره‌محور
finderها، Save، Removeچه چیزی در repository می‌آید
گزارش، لیست، paginationچه چیزی نمی‌آید
پرس‌وجوی دامنه‌ای ترکیب‌پذیرالگوی Specification
چه کسی شروع و commit می‌کندRepository و تراکنش
ستون version، compare-and-setهمزمانی خوش‌بینانه در Save
ردیف به aggregate، سازندهٔ خصوصیReconstitution
Eloquent به‌عنوان aggregate، نگاشت، query builderسه راهبرد Laravel
fake و contract testFake و contract test
کش در repositoryکش
رویدادهایی که aggregate ثبت می‌کندانتشار رویداد هنگام ذخیره
Repository<T> عمومی، DAO، نشتضدالگوها
مثال در GoGo
مثال در LaravelLaravel
هر context و هر سرویسدر معماری
عملیآزمایشگاه
باورهای غلط، خلاصه، آزمون، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

واژگان. هر ردیف بعداً در فهرست مفاهیم باز می‌شود.

اصطلاحبه زبان سادهمثال کوچکبدون آن چه می‌شود
Repositoryدری شبیه مجموعه به aggregateهای ذخیره‌شدهٔ یک نوع ریشهOrderRepository.Get(id) یک Order کامل می‌دهدSQL و نام جدول در use caseها پخش می‌شود
«ریشهٔ اگریگیت (Aggregate Root)»تنها entityای که بیرونی‌ها حق دارند نگه دارند و بخواهندOrder نه OrderLineخطوط پشت سر ریشه ذخیره می‌شوند
Collection-orientedشبیه set: Add و Remove، بدون saveHibernate session، Doctrine با persist و flushبه change tracking نیاز دارید که شاید ندارید
Persistence-orientedبعد از هر تغییر Save صریحorders.Save(ctx, order)فراموش کردن save
Specificationقاعدهٔ دامنه با نام و قابل ترکیب برای انتخاب aggregateUnpaidLongerThan(now, 48h)منطق پرس‌وجو در سرویس‌ها تکرار می‌شود
Unit of Workمرز یک commit، در مالکیت سرویس برنامهDB::transaction(...)، UnitOfWork.Dorepository نصفهٔ یک use case را commit می‌کند
«همزمانی خوش‌بینانه (Optimistic Concurrency)»تشخیص نوشتن رقیب با شمارهٔ versionUPDATE ... WHERE version = $loadedLost update بی‌صدا
Reconstitutionساختن aggregate از state ذخیره‌شده بدون اجرای دستورsales.Reconstitute(snapshot)state نامعتبر وارد می‌شود یا هنگام load رویداد می‌سوزد
Read Modelشکل فقط‌خواندنی برای صفحه یا گزارشOrderListRow از یک viewلیست‌ها aggregate را مجبور می‌کنند همه‌چیز را بیاورد

سه شکل از یک رابط (مقایسه در مجموعه‌محور در برابر ذخیره‌محور):

سبکمتدهاچه کسی تغییر را می‌فهمدخانهٔ طبیعیهزینه
Collection-orientedAdd، Remove، Get، finderunit of work ORM هنگام flushHibernate، Doctrine ORM، EF Coreidentity map و change tracking لازم است
Persistence-orientedGet، Save، Remove، finderفراخوان با صدا زدن SaveGo، Eloquent، key-value و document storeیک فراخوانی بیشتر که باید یادتان بماند
Closure-style updateUpdate(ctx, id, func(*Order) error)خود repository دور closure شماGo (Three Dots Labs)شکل closure تراکنش را پنهان می‌کند

هر پرسش به کجا می‌رود:

پرسشپاسخ ازچرا
«سفارش ۴۲ را بده تا لغوش کنم»OrderRepository.Getدستور به کل aggregate و invariantهایش نیاز دارد
«سفارش‌های ثبت‌شده که دو روز پرداخت نشده‌اند»Repository با specification، یا read modelپرس‌وجوی دامنه؛ نتیجهٔ کوچک؛ هر مورد هدف یک دستور است
«صفحهٔ ۳ لیست سفارش‌ها با جمع کل»Query service / read modelدستور نیست؛ aggregate شکل مناسبی نیست
«درآمد به تفکیک بخش مشتری»انبار گزارشتجمیع بین aggregateها
«این سفارش را ذخیره کن و به Billing خبر بده»Save هم state هم رویداد را در یک تراکنش می‌نویسدنوشتن اتمیک، انتشار بعداً (outbox)

راهبردهای Laravel در یک نگاه (جزئیات در سه راهبرد Laravel):

گزینهشیء دامنهRepositoryبهترین جاهزینهٔ صادقانه
۱. Eloquent خودِ aggregate استمدل Eloquentنازک یا هیچcontextهای CRUD، تیم کوچکsave()، update() و mass assignment عمومی می‌مانند
۲. نگاشت‌شدهکلاس خالص PHPOrderRecord را به Order نگاشت می‌کندinvariantهای واقعی، تست بدون دیتابیسکد نگاشت، دو کلاس برای هر جدول
۳. Query builderکلاس خالص PHPردیف‌های DB::table() با دست نگاشت می‌شوندمسیرهای داغ، schema عجیب، بارگذاری انبوهبیشترین کد، بدون کمک relation

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

مدل دامنه وقتی بی‌فایده است که درآوردن یک aggregate از دیتابیس آن‌قدر دردناک باشد که توسعه‌دهنده‌ها دست بکشند و SQL را در use case بنویسند. Evans شکست را نام می‌برد: "The sheer technical complexity of applying most database access infrastructure quickly swamps the client code, which leads developers to dumb-down the domain layer, which makes the model irrelevant." شکست دوم عکس آن است: پرس‌وجوهای بی‌قید "pull specific fields from objects, breaching encapsulation, or instantiate a few specific objects from the interior of an aggregate, blindsiding the aggregate root and making it impossible for these objects to enforce the rules of the domain model."

Repository سازشی است میان این دو: یک رابط باریک به شکل دامنه که aggregateهای کامل از آن می‌گذرند.

بدون repositoryبا یک repository برای هر ریشه
use caseها SQL می‌سازند و نام جدول را می‌دانندuse caseها Get و Save صدا می‌زنند
هر کدی می‌تواند order_lines را مستقیم به‌روز کندفقط ریشه load و save می‌شود پس قواعدش اجرا می‌شوند
عوض کردن ذخیره‌سازی همهٔ use caseها را درگیر می‌کندعوض کردن ذخیره‌سازی یک کلاس را درگیر می‌کند
تست واحد دیتابیس می‌خواهدتست واحد از repository درون‌حافظه استفاده می‌کند
پرس‌وجوها پخش و تکراریپرس‌وجوهای دامنه نام و یک خانه دارند
مناسب: اسکریپت و گزارشمناسب: مدلی با invariantهای واقعی

قیاسی که در این صفحه تکرار می‌کنیم: میز امانت کتابخانه. شما در قفسه‌ها نمی‌گردید. از میز می‌خواهید «مجموعهٔ کامل این دایرةالمعارف» و کل مجموعه را می‌گیرید؛ جلد ۳ را تنها نمی‌برید و صفحه‌ای از دایرةالمعارف دیگر جایش نمی‌گذارید. وقتی پس می‌دهید، میز کامل بودن را بررسی می‌کند. اگر خواننده‌ای دیگر در این فاصله همان مجموعه را با صفحه‌های متفاوت پس داده باشد، میز پس‌دادن شما را رد می‌کند (این همان بررسی version است). پرسیدن «چند کتاب جلد قرمز دارید؟» خدمت دیگری است: فهرست‌برگه، نه میز امانت (یعنی read model).

Applicationservice (tx)domain layer: one aggregate = one consistency boundaryOrderRepository (interface)Get · Save · Remove · FindSatisfyingOrder (root)version, statusOrderLine ×ninternal entitiesloaded and saved whole, always through the rootPostgres / Eloquentimplementation (infrastructure)ordersorder_linesoutboxone transactionno OrderLineRepositorylines have no door of their owndirect line writes

تصویر نشان می‌دهد رابط repository داخل لایهٔ دامنه است، پیاده‌سازی بیرون آن، و aggregate کامل از مرز می‌گذرد. خطوط (lines) دری برای خودشان ندارند.

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

  1. «Repository پوششی دور ORM یا جدول است.» Repository پوششی دور یک aggregate است. یک جدول ممکن است به سه aggregate خدمت کند و یک aggregate ممکن است چهار جدول را بگیرد.
  2. «Repository برای این است که دیتابیس را عوض کنیم.» این یک اثر جانبی خوب است. هدف، دور نگه داشتن ماندگاری از مدل و دادن یک ورودی واحد به invariantهاست. Three Dots Labs صریح می‌گوید: "If you can swap the database, it's a sign that you implemented the repository pattern correctly"؛ یعنی محکی برای درستی الگو، نه هدف آن.
  3. «هر entity یک repository می‌خواهد.» فقط ریشه‌ها. Evans: "Provide repositories only for aggregate roots that actually need direct access."

از کجا آمده ​

Fowler و Hieatt/Mee، ۲۰۰۳. کتاب Patterns of Enterprise Application Architecture مدخل Repository را از Edward Hieatt و Rob Mee دارد: "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." این الگو روی Data Mapper می‌نشیند؛ "Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes." توجه کنید repository در PoEAA «query specification» می‌گیرد؛ پیوند به مقالهٔ بعدی.

Evans، ۲۰۰۳. کتاب Domain-Driven Design (فصل ۶، "The Life Cycle of a Domain Object") Repository را کنار Aggregate و Factory می‌گذارد: aggregate واحد سازگاری را می‌دهد، factory می‌سازد، repository پیدا و ذخیره می‌کند. DDD Reference (۲۰۱۵) صورت کوتاهی دارد که در این صفحه نقل می‌کنیم.

Evans و Fowler، Specifications. مقاله‌ای از Eric Evans و Martin Fowler: "The central idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched against." سه پیاده‌سازی نام می‌برد: Hard Coded، Parameterized و Composite Specification، و الگوی Subsumption.

Vernon، ۲۰۱۳. کتاب Implementing Domain-Driven Design فصل ۱۲ «Repositories»، الگو را به دو سبک تقسیم می‌کند: repositoryهای collection-oriented که توصیف اصلی Evans را دنبال می‌کنند (بدون مرحلهٔ save) و repositoryهای persistence-oriented برای storeهایی که تغییر را دنبال نمی‌کنند (key-value، data grid) و باید save صدا بزنید. ما فقط خلاصهٔ یک نتیجهٔ جست‌وجو از این فصل را خواندیم (صفحه‌های O'Reilly و Safari به fetcher ما ۴۰۳ دادند)، پس دو سبک را با کلمات خودمان می‌گوییم و از Vernon نقل مستقیم نمی‌آوریم. فصل همچنین پیاده‌سازی با Hibernate، TopLink، Coherence و MongoDB و تفاوت repository با DAO را پوشش می‌دهد (از همان خلاصه).

Khononov، ۲۰۲۱. کتاب Learning Domain-Driven Design در فهرست منابع این فصل به‌عنوان پیش‌زمینهٔ aggregate و دامنهٔ تراکنش است. برای این فصل آن را نگرفتیم و نخواندیم، پس چیزی نقل نمی‌کنیم و ادعایی به آن نسبت نمی‌دهیم.

Microsoft، راهنمای میکروسرویس .NET. "You should only define one repository for each aggregate root"؛ "you should never create a repository for each table in the database". همان قاعده، پشتهٔ دیگر.

Three Dots Labs، ۲۰۲۰. مقالهٔ Robert Laszczak با عنوان The Repository pattern in Go یک رابط با سه پیاده‌سازی (Firestore، MySQL، درون‌حافظه) و تابع update به‌شکل closure برای تراکنش نشان می‌دهد؛ ایده‌هایش را در بخش Go به کار می‌بریم.

text
     سال    منبع                              چه مشکلی را حل کرد
1    2003   PoEAA: Repository                لایهٔ مجموعه‌مانند روی data mapper
2    2003   Evans, DDD, ch. 6                 یک repository برای هر ریشه؛ پرس‌وجو به زبان دامنه
3    2003+  Evans and Fowler, Specification   قواعد انتخاب نام‌دار و ترکیب‌پذیر
4    2013   Vernon, IDDD ch. 12               collection-oriented در برابر persistence-oriented
5    2015   DDD Reference                     عبارت کوتاه هنجاری
6    2020   Three Dots Labs (Go)              update با closure؛ تست به سبک contract
7    2021   Khononov                          پیش‌زمینهٔ aggregate و تراکنش (نخوانده)

Repository چیست ​

Repository شیئی است (رابط در دامنه، پیاده‌سازی در infrastructure) که:

  1. برای هر ریشهٔ aggregate تعریف می‌شود (نه برای entity، نه برای جدول)؛
  2. aggregate کامل و معتبر برمی‌گرداند (نه entity نیمه‌بارشده از درون)؛
  3. aggregate کامل را برای ذخیره می‌گیرد پس invariantها چون ریشه درگیر بود اجرا می‌شوند؛
  4. finderهایی به زبان دامنه دارد (FindSatisfying(UnpaidLongerThan(...))) نه فیلتر عمومی روی فیلد؛
  5. فناوری ذخیره، schema و زبان پرس‌وجو را پنهان می‌کند؛
  6. مالک تراکنش نیست: به تراکنشی می‌پیوندد که سرویس برنامه باز کرده.
text
     فراخوان (سرویس برنامه)                      Repository                         دیتابیس
1    BEGIN (unit of work) ------------------------------------------------------>  BEGIN
2    Get(id) -------------------------------> SELECT order + lines  ----------->  rows
3                                              Reconstitute(snapshot)
4    order.Place(now)   // قواعد دامنه، رویداد در خود aggregate ثبت می‌شود
5    Save(order) ---------------------------> UPDATE ... WHERE version = N ----->  1 row
6                                              replace lines, INSERT outbox  ---->  rows
7    COMMIT --------------------------------------------------------------------->  COMMIT

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

مجموعه‌محور در برابر ذخیره‌محور حیاتی ​

به زبان ساده: repository مجموعه‌محور مثل یک Set<Order> رفتار می‌کند: سفارش را Add می‌کنید، عوضش می‌کنید و سیستم خودش تغییر را می‌فهمد. repository ذخیره‌محور مجبورتان می‌کند هر بار Save بگویید.

بدفهمی رایج: «در DDD repository متد Save ندارد، پس وجود Save یعنی اشتباه می‌کنید.» استعارهٔ مجموعهٔ Evans فرض می‌کند ORM شما session دارد که تغییر را دنبال می‌کند (Hibernate، Doctrine ORM، EF Core). بدون change tracking، رابط صادقانه Save دارد. Go هیچ persistence context ندارد و مدل‌های Eloquent در طول request identity map ندارند، پس ذخیره‌محور در آن‌ها طبیعی است.

تعریف: در repository collection-oriented رابط Add، Remove، Get و finder دارد؛ unit of work با identity map و مقایسهٔ snapshot تغییرها را هنگام commit می‌نویسد. در repository persistence-oriented رابط Save (درج یا به‌روزرسانی)، Remove، Get و finder دارد؛ فراخوان باید بعد از هر تغییر Save صدا بزند.

text
     Collection-oriented                       Persistence-oriented
1    order = orders.Get(id)                    order = orders.Get(id)
2    order.AddLine(...)                        order.AddLine(...)
3    -- هیچ --                                 orders.Save(order)   // صریح
4    uow.Commit()  // مقایسه با snapshot       tx.Commit()
5    -> UPDATE را unit of work می‌فرستد         -> UPDATE را Save می‌فرستد

سناریوی واقعی: سرویس Java روی Hibernate orders.add(order) می‌زند و به flush تکیه می‌کند. سرویس Go روی pgx Save صدا می‌زند. برنامهٔ Laravel $repo->save($order) می‌زند چون Eloquent فقط attributeهای dirty هر نمونه را دنبال می‌کند، نه کل aggregate را.

پشتهردیابی تغییر در کل aggregateسبک طبیعینکته
Hibernate / JPA (Java)persistence context، dirty checkingCollection-orientedpersist، flush هنگام commit
Doctrine ORM (PHP)UnitOfWork، persist، flushCollection-orientedDoctrine لازم است، نه Eloquent
EF Core (.NET)Change trackerCollection-orientedMicrosoft: DbContext هم repository است هم unit of work
Eloquent (Laravel)isDirty() برای هر مدل، بدون identity mapPersistence-orientedrelationها مدل جدا هستند
Go database/sql، pgx، sqlcهیچPersistence-orientedSQL را خودتان می‌نویسید
GORM، ent (Go)به‌ازای هر فراخوانی، بدون session ماندگارPersistence-orientedتراکنش با db.Transaction، client.Tx
MongoDB، Redis، DynamoDBهیچPersistence-orientedجایگزینی کل سند طبیعی است

راه‌حل / نحوهٔ استفاده: در Go و Laravel ذخیره‌محور را بردارید. اگر تیم روی معنای مجموعه اصرار دارد، unit of work کوچک بخش Go را بسازید یا به Doctrine بروید؛ وانمود نکنید Eloquent aggregate را دنبال می‌کند.

go
// Package style contrasts the two repository styles from Vernon's chapter 12.
// A collection-oriented repository has Add/Remove and NO save: changes to
// loaded aggregates are noticed by a unit of work (identity map + snapshot
// diff, what Hibernate and Doctrine do). Go and Eloquent do not track changes
// for you, so this file shows the machinery you would have to build.
package style

import (
	"context"
	"reflect"

	"academy/repositories/sales"
)

// Store is the low-level persistence-oriented port the collection wraps.
type Store interface {
	Get(ctx context.Context, id sales.OrderID) (*sales.Order, error)
	Save(ctx context.Context, o *sales.Order) error
	Remove(ctx context.Context, id sales.OrderID) error
}

// OrderCollection is collection-oriented: Add, Remove, Get. There is no Save.
type OrderCollection interface {
	Add(o *sales.Order)
	Remove(id sales.OrderID)
	Get(ctx context.Context, id sales.OrderID) (*sales.Order, error)
}

// TrackedCollection is a unit of work in miniature. It remembers what it
// handed out and, at Commit, writes back whatever changed.
type TrackedCollection struct {
	store    Store
	identity map[sales.OrderID]*sales.Order   // identity map: one instance per id
	original map[sales.OrderID]sales.Snapshot // state when loaded
	added    map[sales.OrderID]bool
	removed  map[sales.OrderID]bool
}

// NewTracked returns a collection backed by store.
func NewTracked(store Store) *TrackedCollection {
	return &TrackedCollection{store: store,
		identity: map[sales.OrderID]*sales.Order{}, original: map[sales.OrderID]sales.Snapshot{},
		added: map[sales.OrderID]bool{}, removed: map[sales.OrderID]bool{}}
}

func (c *TrackedCollection) Add(o *sales.Order) {
	c.identity[o.ID()] = o
	c.added[o.ID()] = true
}

func (c *TrackedCollection) Remove(id sales.OrderID) { c.removed[id] = true }

func (c *TrackedCollection) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	if o, ok := c.identity[id]; ok {
		return o, nil
	}
	o, err := c.store.Get(ctx, id)
	if err != nil {
		return nil, err
	}
	c.identity[id] = o
	c.original[id] = o.Snapshot()
	return o, nil
}

// Commit is the flush: new -> Save, changed -> Save, removed -> Remove.
// A caller who forgets Commit loses the change silently; that is the price of
// "no explicit save" in a language without a persistence context.
func (c *TrackedCollection) Commit(ctx context.Context) error {
	for id := range c.removed {
		if err := c.store.Remove(ctx, id); err != nil {
			return err
		}
	}
	for id, o := range c.identity {
		if c.removed[id] {
			continue
		}
		dirty := c.added[id] || !reflect.DeepEqual(c.original[id], o.Snapshot())
		if dirty {
			if err := c.store.Save(ctx, o); err != nil {
				return err
			}
		}
	}
	return nil
}
Collection-oriented (Add / Remove)Persistence-oriented (Get / Save)orders.Get(id)order.AddLine(...)(nothing: no save)Unit of workidentity mapsnapshot diffflush on commitorders.Get(id)order.AddLine(...)orders.Save(order)RepositoryUPDATE ... WHEREversion = loaded0 rows = conflictHibernate, Doctrine ORM, EF Core track for youForget commit: change silently lostGo, Eloquent, key-value stores: explicitForget Save: change silently lost, but visible in code

چه چیزی در repository می‌آید حیاتی ​

به زبان ساده: یکی را با id بگیر، ذخیره کن، حذف کن، و فقط چند پرسشی را بپرس که خود دامنه می‌پرسد.

بدفهمی رایج: «repository باید هر پرس‌وجویی را که صفحه‌ها لازم دارند عرضه کند.» صفحه‌ها لیست، فیلتر، جمع و مرتب‌سازی می‌خواهند؛ aggregate شکل نادرست و repository جای نادرست است. رابط را به آنچه دستورها لازم دارند محدود کنید.

تعریف: حداقل Get(id)، Save(aggregate) و در صورت وجود حذف، Remove(id) است. finder فقط وقتی اضافه شود که use case باید aggregateها را با چیزی غیر از id پیدا کند و بعد رویشان عمل کند (FindSatisfying(spec)، FindOverdue(now)). اگر هویت را مدل می‌دهد NextID() هم اضافه کنید.

متدمی‌آید؟دلیل
Get(ctx, id)بلههر دستور از اینجا شروع می‌شود
Save(ctx, order)بلهدرج یا به‌روزرسانی با بررسی version
Remove(ctx, id)بله، اگر سفارش حذف می‌شودبسیاری از دامنه‌ها به‌جای حذف لغو می‌کنند
FindSatisfying(ctx, spec)بلهپرس‌وجوی دامنه که دستور را تغذیه می‌کند
NextID()اغلبمدل قبل از ذخیره هویت می‌دهد
GetAll()به‌ندرتنامحدود؛ از query service استفاده کنید
Count()، Exists()به‌ندرتگزارش یا نگهبان؛ Get را بسنجید
Paginate(page, size)خیردغدغهٔ UI؛ سمت پرس‌وجو
Where(field, op, value)خیرschema را نشت می‌دهد
UpdateStatus(id, status)خیرریشه را دور می‌زند
Raw(sql, args...)خیرdialect را نشت می‌دهد
text
     قاعدهٔ سرانگشتی برای finder
1    آیا use case نتیجه را LOAD می‌کند و روی آن دستور می‌زند؟   بله -> finder در repository
2    آیا فقط نمایش یا خلاصه می‌کند؟                              بله -> query service
3    آیا از aggregateها یا contextها می‌گذرد؟                     بله -> read model

چه چیزی نمی‌آید: گزارش، لیست و pagination حیاتی ​

به زبان ساده: اگر صفحه نشانش می‌دهد، aggregate چیز مناسبی برای load کردن نیست.

بدفهمی رایج: «CQRS یک فریم‌ورک بزرگ است پس نمی‌توانیم خواندن را جدا کنیم.» جداسازی می‌تواند یک کلاس اضافه باشد: query service که SQL اجرا می‌کند و DTO تخت برمی‌گرداند. بحث کامل CQRS در Data Patterns و صفحه‌بندی keyset در Pagination.

تعریف: پرس‌وجوهایی که داده برای نمایش برمی‌گردانند (لیست، داشبورد، خروجی، جمع) repository و aggregate را دور می‌زنند و روی query service یا read model اجرا می‌شوند که حتی می‌تواند جدول یا دیتابیس دیگری باشد. اجازه دارند eventually consistent باشند؛ دستورها نه.

نیازخانهپیاده‌سازی
لیست سفارش‌ها برای صفحهٔ مشتریQuery serviceSELECT ... LIMIT با keyset به یک DTO
جست‌وجوی ادمین با فیلترQuery serviceQuery builder یا موتور جست‌وجو
درآمد روزانهانبار گزارشmaterialised view، data warehouse
«این SKU هنوز قابل فروش است؟»Catalog API یا read modelدادهٔ context دیگر، هرگز repository بین contextها
سفارش‌هایی که بعد از ۴۸ ساعت باید لغو شوندRepository + specificationهر نتیجه بعداً هدف دستور است
text
     صفحهٔ لیست سفارش‌ها
1    GET /orders?customer=c-1&page=3
2    OrderQueries.ListFor(customer, cursor)     -- query service، نه repository
3    SELECT id, status, total_minor, placed_at FROM orders WHERE customer_id = $1 AND (placed_at, id) < ($2, $3) ORDER BY placed_at DESC, id DESC LIMIT 20
4    -> []OrderListRow (DTO تخت)، هیچ aggregate و هیچ line بارگذاری نشد

الگوی Specification برای پرس‌وجوی دامنه مهم ​

به زبان ساده: به یک قاعدهٔ دامنه نام بدهید و بگذارید با And، Or، Not ترکیب شود تا repository بتواند بگوید «هرچه این قاعده را برآورده می‌کند پیدا کن».

بدفهمی رایج: «specification یک query builder با مراحل اضافه است.» specification می‌گوید دامنه چه معنی دارد («بیش از ۴۸ ساعت پرداخت‌نشده»)؛ query builder می‌گوید دیتابیس چطور پیدایش کند. همان specification را می‌شود در حافظه روی یک aggregate تست کرد یا برای چندتا به SQL ترجمه کرد.

تعریف: Spec متد IsSatisfiedBy(candidate) bool دارد. specificationهای ترکیبی (And، Or، Not) آن‌ها را می‌چسبانند. FindSatisfying(spec) در repository یا specificationهای شناخته‌شده را به SQL ترجمه می‌کند یا مجموعهٔ بزرگ‌تری را می‌آورد و در حافظه فیلتر می‌کند.

text
     سه کاربرد Specification
1    اعتبارسنجی:  spec.IsSatisfiedBy(order)                -- یک aggregate در حافظه
2    انتخاب:      orders.FindSatisfying(spec)              -- repository به SQL ترجمه می‌کند
3    ساخت:        factory سفارشی می‌سازد که spec را برآورده کند -- کاربرد سوم Evans و Fowler

ترجمه به SQL و محدودیت‌ها. repository یک مترجم دارد: type switch روی specificationهایی که می‌شناسد (ForCustomer، InStatus، PlacedBefore، AndSpec، OrSpec، NotSpec). specification ناشناخته خطاست، نه اسکن کامل بی‌صدا. محدودیت‌های مهم:

محدودیتچرادرمان
قاعدهٔ دامنه منطقی دارد که SQL نمی‌تواند بیان کندفراخوانی متد روی aggregate که سه line را می‌خواندبا SQL درشت پیش‌فیلتر کنید، بعد IsSatisfiedBy در حافظه
هر spec جدید یک شاخهٔ مترجم می‌خواهدopen/closed در repository می‌شکندفهرست را کوتاه نگه دارید؛ برای قاعدهٔ داغ finder اختصاصی بنویسید
اندازهٔ نتیجه نامحدود استspecification وسیع هزاران aggregate می‌آوردبه finder limit بدهید یا query service
کارایی به indexهایی بستگی دارد که spec نمی‌داندplaced_at < $1 به index نیاز داردindex را با spec اضافه کنید؛ plan را ببینید
قاعده‌های بین aggregate«مشتری‌هایی با ۳ سفارش پرداخت‌نشده»query service یا read model

سناریوی واقعی: کار شبانهٔ Billing: orders.FindSatisfying(UnpaidLongerThan(now, 48h))، سپس برای هر نتیجه order.Cancel("payment timeout") و Save. نام قاعده همان زبان فراگیر است («unpaid longer than») و همان spec در تست واحد بدون دیتابیس استفاده می‌شود.

راه‌حل / نحوهٔ استفاده:

sql
-- What the Go translator emits for UnpaidLongerThan(now, 48h)
SELECT id, customer_id, currency, status, placed_at, version
FROM orders
WHERE (status = $1 AND placed_at < $2)   -- $1 = 'placed', $2 = now - 48h
ORDER BY id;
-- supported by: CREATE INDEX orders_status_placed_at ON orders (status, placed_at);
go
package sales

import "time"

// Spec is a domain rule that can test an aggregate in memory. Repositories
// may also translate known specs to SQL (see postgres/spec.go).
type Spec interface {
	IsSatisfiedBy(o *Order) bool
}

// ForCustomer matches orders of one customer.
type ForCustomer struct{ ID CustomerID }

// InStatus matches orders in one state.
type InStatus struct{ Status Status }

// PlacedBefore matches orders placed strictly before T.
type PlacedBefore struct{ T time.Time }

// AndSpec, OrSpec and NotSpec are the composite specification.
type (
	AndSpec struct{ Specs []Spec }
	OrSpec  struct{ Specs []Spec }
	NotSpec struct{ Spec Spec }
)

func (s ForCustomer) IsSatisfiedBy(o *Order) bool { return o.customer == s.ID }
func (s InStatus) IsSatisfiedBy(o *Order) bool    { return o.status == s.Status }
func (s PlacedBefore) IsSatisfiedBy(o *Order) bool {
	return !o.placedAt.IsZero() && o.placedAt.Before(s.T)
}

func (s AndSpec) IsSatisfiedBy(o *Order) bool {
	for _, c := range s.Specs {
		if !c.IsSatisfiedBy(o) {
			return false
		}
	}
	return true
}

func (s OrSpec) IsSatisfiedBy(o *Order) bool {
	for _, c := range s.Specs {
		if c.IsSatisfiedBy(o) {
			return true
		}
	}
	return false
}

func (s NotSpec) IsSatisfiedBy(o *Order) bool { return !s.Spec.IsSatisfiedBy(o) }

// And, Or and Not read better at call sites than the struct literals.
func And(s ...Spec) Spec { return AndSpec{Specs: s} }
func Or(s ...Spec) Spec  { return OrSpec{Specs: s} }
func Not(s Spec) Spec    { return NotSpec{Spec: s} }

// UnpaidLongerThan is the domain-language query "placed, still unpaid after d".
// The name lives in the model; the SQL does not leak into callers.
func UnpaidLongerThan(now time.Time, d time.Duration) Spec {
	return And(InStatus{Placed}, PlacedBefore{now.Add(-d)})
}
go
package postgres

import (
	"errors"
	"fmt"
	"strings"

	"academy/repositories/sales"
)

// ErrUnsupportedSpec is returned for a specification this repository cannot
// express in SQL. The caller may load a superset and filter in memory.
var ErrUnsupportedSpec = errors.New("specification cannot be translated to SQL")

// toSQL turns a known specification into a WHERE fragment with $n placeholders
// numbered from start. The set of translatable specs is deliberately small:
// it is the list of queries the domain actually asks.
func toSQL(spec sales.Spec, start int) (string, []any, error) {
	switch s := spec.(type) {
	case sales.ForCustomer:
		return fmt.Sprintf("customer_id = $%d", start), []any{string(s.ID)}, nil
	case sales.InStatus:
		return fmt.Sprintf("status = $%d", start), []any{string(s.Status)}, nil
	case sales.PlacedBefore:
		return fmt.Sprintf("placed_at < $%d", start), []any{s.T}, nil
	case sales.NotSpec:
		inner, args, err := toSQL(s.Spec, start)
		if err != nil {
			return "", nil, err
		}
		return "NOT (" + inner + ")", args, nil
	case sales.AndSpec:
		return join(s.Specs, " AND ", start)
	case sales.OrSpec:
		return join(s.Specs, " OR ", start)
	default:
		return "", nil, fmt.Errorf("%w: %T", ErrUnsupportedSpec, spec)
	}
}

func join(specs []sales.Spec, op string, start int) (string, []any, error) {
	if len(specs) == 0 {
		return "", nil, fmt.Errorf("%w: empty composite", ErrUnsupportedSpec)
	}
	parts := make([]string, 0, len(specs))
	var all []any
	for _, c := range specs {
		sql, args, err := toSQL(c, start+len(all))
		if err != nil {
			return "", nil, err
		}
		parts = append(parts, sql)
		all = append(all, args...)
	}
	return "(" + strings.Join(parts, op) + ")", all, nil
}

Repository و تراکنش حیاتی ​

به زبان ساده: use case تراکنش را باز می‌کند؛ repository فقط در آن شریک می‌شود.

بدفهمی رایج: «Save باید commit کند تا داده امن باشد.» اگر Save commit کند، use caseی که دو aggregate (یا یک aggregate و یک ردیف outbox) ذخیره می‌کند دیگر اتمیک نیست و خرابی بین این دو نصفهٔ یک عملیات کسب‌وکار را باقی می‌گذارد. commit مال کسی است که می‌داند use case تمام شده.

تعریف: مرز unit of work سرویس برنامه است (Domain, Application & Infrastructure Services). repositoryها اتصال را از تراکنش جاری، اگر باشد، می‌گیرند. هر use case در هر تراکنش یک aggregate را عوض می‌کند (نگاه کنید Aggregates & Factories)؛ ردیف outbox ردیف دوم در همان تراکنش است.

one transaction owned by the application service; the repository only joins itBEGINrepo.Getversion = 4order.Place()records eventrepo.SaveWHERE version = 4COMMIT0 rows: ErrConcurrentModificationROLLBACK, reload, retry (app decides)Save writes: orders row, order_lines, outbox event
تکنیکGoLaravel
مالک تراکنشسرویس برنامه با UnitOfWork.Do(ctx, fn)DB::transaction(fn) در handler
repository چطور می‌پیونددpgx.Tx در context.Contextاتصال پیش‌فرض که در تراکنش است
جایگزین صریحrepository محدود به tx: repo.WithTx(tx)DB::connection($name)->transaction(...)
سبک closureUpdate(ctx, id, func(*Order) error) (Three Dots Labs)$repo->update($id, fn (Order $o) => ...)
retry هنگام deadlockحلقهٔ خودتان دور DoDB::transaction($cb, attempts: 5)
retry هنگام تعارض versionحلقهٔ صریح در سرویس برنامهحلقهٔ صریح؛ attempts آن را پوشش نمی‌دهد
فراخوانی تودرتومی‌پیوندد (context تراکنش دارد)savepoint (DB::transaction تودرتو)
تستTx جعلی که فقط fn را صدا می‌زندRefreshDatabase هر تست را در تراکنش می‌گذارد

مستندات Laravel می‌گوید متد transaction "accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs." این retry برای deadlock است، نه برای قفل خوش‌بینانه: ConcurrentModification که repository شما پرت می‌کند حلقهٔ خودش را می‌خواهد.

رد کردن تراکنش در Go. سه راه با هزینهٔ صادقانه:

راهچگونهنقطهٔ قوتنقطهٔ ضعف
تراکنش در context.Contextctx = context.WithValue(ctx, txKey{}, tx)؛ repository می‌خواندامضا عوض نمی‌شود؛ repository کوچک می‌ماندوابستگی پنهان؛ فراموش کردن ctx مشتق‌شده آسان است
repository محدود به txrepos := postgres.New(tx) برای هر use caseصریح، در زمان کامپایل دیده می‌شودfactory به‌ازای هر use case؛ wiring بزرگ می‌شود
update با closurerepository خودش Get، fn شما و Save را در تراکنش خود اجرا می‌کندتراکنش نشت نمی‌کندفقط به use caseهای load-modify-save می‌خورد

Three Dots Labs رویکرد context را آزمایش کرده و می‌گوید در آزمایش‌هایشان "a bit magical, not explicit, and slow in some cases" بود و closure را ترجیح می‌دهد؛ ما رویکرد context را نشان می‌دهیم چون رابط را کوچک نگه می‌دارد، و این را صریح می‌گوییم.

go
// Package app is the application layer: it owns the transaction, the
// repository does not.
package app

import (
	"context"
	"time"

	"academy/repositories/sales"
)

// Tx runs fn atomically. postgres.UnitOfWork.Do satisfies it.
type Tx interface {
	Do(ctx context.Context, fn func(ctx context.Context) error) error
}

// PlaceOrder is one use case = one transaction = one aggregate.
type PlaceOrder struct {
	Tx     Tx
	Orders sales.OrderRepository
	Now    func() time.Time
}

// Handle loads, runs the domain command, saves. If Save loses an optimistic
// race it reports ErrConcurrentModification and the transaction rolls back;
// whether to retry is decided here, not in the repository.
func (h PlaceOrder) Handle(ctx context.Context, id sales.OrderID) error {
	var err error
	for attempt := 0; attempt < 3; attempt++ {
		err = h.Tx.Do(ctx, func(ctx context.Context) error {
			o, err := h.Orders.Get(ctx, id)
			if err != nil {
				return err
			}
			if err := o.Place(h.Now()); err != nil {
				return err
			}
			return h.Orders.Save(ctx, o)
		})
		if err != sales.ErrConcurrentModification {
			return err
		}
	}
	return err
}

همزمانی خوش‌بینانه در Save حیاتی ​

به زبان ساده: هر aggregate ذخیره‌شده یک شمارهٔ version دارد؛ Save فقط وقتی موفق می‌شود که شماره هنوز همانی باشد که load کردید.

بدفهمی رایج: «تراکنش خودش جلوی بازنویسی دو کاربر را می‌گیرد.» در READ COMMITTED (پیش‌فرض PostgreSQL) دو تراکنش می‌توانند هر دو version 4 را بخوانند، هر دو سفارش را عوض کنند، و UPDATE دوم اولی را بی‌صدا بازنویسی کند. تراکنش اتمیک بودن می‌دهد، نه «از وقتی خواندم کسی عوضش نکرده». نگاه کنید Isolation Levels.

تعریف: aggregate یک version دارد (۰ یعنی هرگز ذخیره نشده). Save اجرا می‌کند UPDATE ... SET version = version + 1 WHERE id = $1 AND version = $loaded. صفر ردیف یعنی دیگری زودتر ذخیره کرده: ErrConcurrentModification برگردانید؛ سرویس برنامه دوباره load می‌کند و دستور را دوباره اجرا می‌کند. مقایسه کنید Optimistic vs Pessimistic Locking.

text
     کاربر A                               کاربر B                              version در DB
1    Get(order 7) -> v4                    Get(order 7) -> v4                   4
2    order.MarkPaid()                      order.Cancel()
3    Save: UPDATE ... WHERE version=4
     1 row, version := 5                                                        5
4                                          Save: UPDATE ... WHERE version=4
                                           0 rows -> ErrConcurrentModification  5
5                                          Reload (v5, paid)، حالا Cancel() قاعدهٔ دامنه را نقض می‌کند
موتور / storeسازوکار versionنکته
PostgreSQLستون integer به نام version، یا ستون سیستمی xminxmin با هر به‌روزرسانی عوض می‌شود اما شناسهٔ تراکنش ۳۲ بیتی است و wrap می‌شود؛ ستون صریح بهتر است
MySQL / InnoDBversion عددی یا updated_at با میکروثانیهupdated_at زیر بار برخورد می‌کند؛ عدد بهتر است
SQL Serverستون rowversionخودکار، باینری
OracleORA_ROWSCN یا ستون versionستون صریح قابل‌حمل است
MongoDBfindOneAndUpdate با فیلتر {_id, version}اتمیک بودن تک‌سند
DynamoDBنوشتن شرطی: ConditionExpression: version = :vروش استاندارد
RedisWATCH / MULTI / EXECذاتاً خوش‌بینانه
Hibernate / JPA@Versionخودکار
Eloquentداخلی نداردWHERE version را خودتان بگذارید
GORMبه‌طور پیش‌فرض داخلی نداردgorm.io/plugin/optimisticlock یک plugin است؛ پیش از استفاده مستنداتش را ببینید

دو قاعده: version فقط در ریشهٔ aggregate است (نه برای هر line)، و repository فقط بعد از موفقیت همهٔ دستورها آن را بالا می‌برد.

go
// Package postgres implements sales.OrderRepository with pgx. The repository
// never commits a transaction it did not start: if the caller put a pgx.Tx in
// the context (see UnitOfWork), every statement joins it; otherwise Save opens
// and commits its own short transaction.
package postgres

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"

	"academy/repositories/sales"
)

// DBTX is satisfied by *pgxpool.Pool and pgx.Tx; sqlc generates the same
// interface, which is why sqlc code works inside and outside a transaction.
type DBTX interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

type txKey struct{}

// UnitOfWork runs fn in one transaction; repositories called with the ctx it
// passes join that transaction. This is the application layer's tool: the
// repository itself has no Begin/Commit.
type UnitOfWork struct{ Pool *pgxpool.Pool }

// Do begins a transaction, runs fn, commits on nil and rolls back on error.
func (u UnitOfWork) Do(ctx context.Context, fn func(ctx context.Context) error) error {
	tx, err := u.Pool.Begin(ctx)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback(ctx) }() // no-op after Commit
	if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
		return err
	}
	return tx.Commit(ctx)
}

// Repository is the Postgres implementation.
type Repository struct{ pool *pgxpool.Pool }

// New returns a repository on the pool.
func New(pool *pgxpool.Pool) *Repository { return &Repository{pool: pool} }

func (r *Repository) db(ctx context.Context) DBTX {
	if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
		return tx
	}
	return r.pool
}

func (r *Repository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	db := r.db(ctx)
	var s sales.Snapshot
	var placed *time.Time
	err := db.QueryRow(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE id = $1`, string(id)).
		Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version)
	if errors.Is(err, pgx.ErrNoRows) {
		return nil, sales.ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	if placed != nil {
		s.PlacedAt = *placed
	}
	lines, err := r.lines(ctx, db, []string{string(id)})
	if err != nil {
		return nil, err
	}
	s.Lines = lines[id]
	return sales.Reconstitute(s)
}

func (r *Repository) lines(ctx context.Context, db DBTX, ids []string) (map[sales.OrderID][]sales.LineSnapshot, error) {
	rows, err := db.Query(ctx, `SELECT order_id, sku, quantity, unit_price_minor FROM order_lines WHERE order_id = ANY($1::text[]) ORDER BY order_id, sku`, ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[sales.OrderID][]sales.LineSnapshot{}
	for rows.Next() {
		var oid sales.OrderID
		var l sales.LineSnapshot
		if err := rows.Scan(&oid, &l.SKU, &l.Quantity, &l.UnitPriceMinor); err != nil {
			return nil, err
		}
		out[oid] = append(out[oid], l)
	}
	return out, rows.Err()
}

func (r *Repository) Save(ctx context.Context, o *sales.Order) error {
	if _, inTx := ctx.Value(txKey{}).(pgx.Tx); !inTx {
		// Standalone call: open our own short transaction and join it.
		return UnitOfWork{Pool: r.pool}.Do(ctx, func(ctx context.Context) error { return r.Save(ctx, o) })
	}
	db := r.db(ctx)
	s := o.Snapshot()
	var placed *time.Time
	if !s.PlacedAt.IsZero() {
		placed = &s.PlacedAt
	}
	next := s.Version + 1
	if s.Version == 0 {
		_, err := db.Exec(ctx, `INSERT INTO orders (id, customer_id, currency, status, placed_at, version) VALUES ($1,$2,$3,$4,$5,1)`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed)
		var pgErr *pgconn.PgError
		if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation: someone inserted the same id
			return sales.ErrConcurrentModification
		}
		if err != nil {
			return err
		}
	} else {
		tag, err := db.Exec(ctx, `UPDATE orders SET customer_id=$2, currency=$3, status=$4, placed_at=$5, version=version+1 WHERE id=$1 AND version=$6`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed, s.Version)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 { // stale version, or the row is gone
			return sales.ErrConcurrentModification
		}
	}
	// The aggregate is stored whole: replace its internal rows.
	if _, err := db.Exec(ctx, `DELETE FROM order_lines WHERE order_id = $1`, string(s.ID)); err != nil {
		return err
	}
	for _, l := range s.Lines {
		if _, err := db.Exec(ctx, `INSERT INTO order_lines (order_id, sku, quantity, unit_price_minor) VALUES ($1,$2,$3,$4)`,
			string(s.ID), string(l.SKU), l.Quantity, l.UnitPriceMinor); err != nil {
			return err
		}
	}
	// Events go to the outbox in the same transaction (no broker call here).
	for _, e := range o.PendingEvents() {
		topic, ok := outboxTopics[e.EventName()]
		if !ok {
			return fmt.Errorf("no published topic for %s", e.EventName())
		}
		payload, err := json.Marshal(e)
		if err != nil {
			return err
		}
		if _, err := db.Exec(ctx, `INSERT INTO outbox (topic, payload) VALUES ($1, $2)`, topic, payload); err != nil {
			return err
		}
	}
	o.Persisted(next) // only after every statement succeeded
	return nil
}

// outboxTopics maps domain event class names to the dotted, versioned topic
// of the published language. Only the outbox row carries the wire name.
var outboxTopics = map[string]string{
	"OrderPlaced": "sales.order.placed.v1",
}

func (r *Repository) Remove(ctx context.Context, id sales.OrderID) error {
	tag, err := r.db(ctx).Exec(ctx, `DELETE FROM orders WHERE id = $1`, string(id)) // lines go by ON DELETE CASCADE
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return sales.ErrNotFound
	}
	return nil
}

func (r *Repository) FindSatisfying(ctx context.Context, spec sales.Spec) ([]*sales.Order, error) {
	where, args, err := toSQL(spec, 1)
	if err != nil {
		return nil, err
	}
	db := r.db(ctx)
	rows, err := db.Query(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE `+where+` ORDER BY id`, args...)
	if err != nil {
		return nil, err
	}
	var snaps []sales.Snapshot
	var ids []string
	for rows.Next() {
		var s sales.Snapshot
		var placed *time.Time
		if err := rows.Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version); err != nil {
			rows.Close()
			return nil, err
		}
		if placed != nil {
			s.PlacedAt = *placed
		}
		snaps = append(snaps, s)
		ids = append(ids, string(s.ID))
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return nil, err
	}
	if len(snaps) == 0 {
		return nil, nil
	}
	lines, err := r.lines(ctx, db, ids) // one query for all lines, not one per order
	if err != nil {
		return nil, err
	}
	out := make([]*sales.Order, 0, len(snaps))
	for _, s := range snaps {
		s.Lines = lines[s.ID]
		o, err := sales.Reconstitute(s)
		if err != nil {
			return nil, fmt.Errorf("order %s: %w", s.ID, err)
		}
		out = append(out, o)
	}
	return out, nil
}

Reconstitution حیاتی ​

به زبان ساده: ساختن دوبارهٔ aggregate از ردیف‌های ذخیره‌شده با «ساختن» فرق دارد، پس نباید قواعد ایجاد را اجرا کند یا رویداد بسوزاند.

بدفهمی رایج: «فقط سازنده را با مقادیر ردیف صدا بزن.» سازنده (یا factory به نام NewOrder) قواعد ایجاد را اعمال و رویداد «ایجاد شد» را ثبت می‌کند؛ صدا زدنش هنگام load تاریخچه را دوباره پخش می‌کند. load مسیر جدا می‌خواهد که به state ذخیره‌شده اعتماد می‌کند ولی چیزهایی را که ردیف خراب می‌تواند بشکند رد می‌کند.

تعریف: Reconstitution ساختن شیء از state ماندگار است. ابزارها: سازندهٔ نام‌دار (Reconstitute(snapshot)، Order::reconstitute($array)) جدا از factory؛ یک snapshot تخت (memento) که در هر دو جهت از مرز می‌گذرد؛ فیلدهای خصوصی تا فقط متدهای ریشه state را عوض کنند.

تکنیکزبانمزیتعیب
Snapshot struct + ReconstituteGoصریح، کامپایلر بررسی می‌کند، بدون reflectionفیلدها سه بار فهرست می‌شوند (struct، snapshot، mapper)
فیلدهای exported روی aggregateGoبدون نگاشتهر کسی state را می‌گذارد؛ invariantها بی‌محافظ
Reflection یا unsafeGoبدون نوع snapshotشکننده، کند، تغییر نام را پنهان می‌کند
سازندهٔ خصوصی + reconstitute ایستاPHPصریحهمان فهرست سه‌باره
ReflectionClass::newInstanceWithoutConstructor + set propertyPHPDoctrine استفاده می‌کندهمهٔ قواعد را دور می‌زند؛ mapper تست‌شده لازم است
Eloquent hydration (newFromBuilder)PHPرایگانمدل هم aggregate است هم ردیف دیتابیس
Serializer (JSON/Symfony Serializer)PHPکوتاههمان دور زدن؛ پیش از اعتماد اعتبارسنجی کنید
reconstitution بایدنباید
همهٔ فیلدها از جمله version را بگذارددستورهایی مثل Place را اجرا کند
invariantهایی را که ردیف خراب می‌شکند بررسی کند (status در enum، quantity حداقل ۱)رویداد OrderPlaced ثبت کند
هر بار نمونهٔ تازه برگرداندنمونهٔ زندهٔ مشترک بین فراخوان‌ها بدهد (خطر کش)
روی status ناشناخته بلند شکست بخوردمقدار ناشناخته را بی‌صدا پیش‌فرض کند
go
// Package sales is the Sales bounded context. Order is the aggregate root;
// the repository in this chapter loads and saves it as one unit.
package sales

import (
	"errors"
	"fmt"
	"time"
)

type (
	// OrderID is the identity of the Order aggregate.
	OrderID string
	// CustomerID references the Identity context's customer by id only.
	CustomerID string
	// SKU references a Catalog product by id only.
	SKU string
)

// Status is the order state machine.
type Status string

const (
	Draft     Status = "draft"
	Placed    Status = "placed"
	Paid      Status = "paid"
	Cancelled Status = "cancelled"
)

var (
	ErrNotEditable = errors.New("only a draft order can be edited")
	ErrEmptyOrder  = errors.New("an order needs at least one line")
	ErrBadQuantity = errors.New("quantity must be at least 1")
	ErrBadStatus   = errors.New("unknown order status")
	ErrBadState    = errors.New("stored state violates an order invariant")
)

// Money is a value object in minor units.
type Money struct {
	Minor    int64
	Currency string
}

type line struct {
	sku       SKU
	quantity  int
	unitPrice int64
}

// Order is the aggregate root. All fields are private: only the root's
// methods change state, only Snapshot/Reconstitute move state across the
// persistence boundary.
type Order struct {
	id       OrderID
	customer CustomerID
	currency string
	status   Status
	lines    []line
	placedAt time.Time
	version  int // optimistic concurrency token; 0 means "never saved"
	events   []Event
}

// NewOrder starts a draft order (the factory for a brand-new aggregate).
func NewOrder(id OrderID, customer CustomerID, currency string) *Order {
	return &Order{id: id, customer: customer, currency: currency, status: Draft}
}

// AddLine adds or merges a line while the order is a draft.
func (o *Order) AddLine(sku SKU, qty int, unitPriceMinor int64) error {
	if o.status != Draft {
		return ErrNotEditable
	}
	if qty < 1 {
		return ErrBadQuantity
	}
	for i := range o.lines {
		if o.lines[i].sku == sku {
			o.lines[i].quantity += qty
			return nil
		}
	}
	o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: unitPriceMinor})
	return nil
}

// Place commits the order and records OrderPlaced for the outbox.
func (o *Order) Place(now time.Time) error {
	if o.status != Draft {
		return fmt.Errorf("place: %w", ErrNotEditable)
	}
	if len(o.lines) == 0 {
		return ErrEmptyOrder
	}
	o.status = Placed
	o.placedAt = now
	o.events = append(o.events, OrderPlaced{OrderID: o.id, Total: o.Total(), At: now})
	return nil
}

// MarkPaid is called when Billing reports a captured payment.
func (o *Order) MarkPaid() error {
	if o.status != Placed {
		return errors.New("only a placed order can be paid")
	}
	o.status = Paid
	return nil
}

// Total is derived from the lines.
func (o *Order) Total() Money {
	var t int64
	for _, l := range o.lines {
		t += l.unitPrice * int64(l.quantity)
	}
	return Money{Minor: t, Currency: o.currency}
}

func (o *Order) ID() OrderID            { return o.id }
func (o *Order) Customer() CustomerID   { return o.customer }
func (o *Order) Status() Status         { return o.status }
func (o *Order) Version() int           { return o.version }
func (o *Order) PlacedAt() time.Time    { return o.placedAt }
func (o *Order) LineCount() int         { return len(o.lines) }
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }

// Persisted is called by repository implementations after a successful save:
// it records the new version and clears the events the repository has stored.
func (o *Order) Persisted(newVersion int) {
	o.version = newVersion
	o.events = nil
}

// LineSnapshot is the flat state of one line.
type LineSnapshot struct {
	SKU            SKU
	Quantity       int
	UnitPriceMinor int64
}

// Snapshot is the flat, exported state of the whole aggregate. It is the
// shape that crosses the persistence boundary in both directions.
type Snapshot struct {
	ID       OrderID
	Customer CustomerID
	Currency string
	Status   Status
	Lines    []LineSnapshot
	PlacedAt time.Time
	Version  int
}

// Snapshot copies the state out (a memento). It never exposes internal slices.
func (o *Order) Snapshot() Snapshot {
	s := Snapshot{ID: o.id, Customer: o.customer, Currency: o.currency, Status: o.status,
		PlacedAt: o.placedAt, Version: o.version}
	for _, l := range o.lines {
		s.Lines = append(s.Lines, LineSnapshot{SKU: l.sku, Quantity: l.quantity, UnitPriceMinor: l.unitPrice})
	}
	return s
}

// Reconstitute rebuilds an aggregate from stored state. It runs no commands,
// records no events, and re-checks only what a corrupt row could break.
func Reconstitute(s Snapshot) (*Order, error) {
	switch s.Status {
	case Draft, Placed, Paid, Cancelled:
	default:
		return nil, fmt.Errorf("%w: %q", ErrBadStatus, s.Status)
	}
	if s.Status != Draft && len(s.Lines) == 0 {
		return nil, fmt.Errorf("%w: %s has no lines", ErrBadState, s.ID)
	}
	o := &Order{id: s.ID, customer: s.Customer, currency: s.Currency, status: s.Status,
		placedAt: s.PlacedAt, version: s.Version}
	for _, l := range s.Lines {
		if l.Quantity < 1 {
			return nil, fmt.Errorf("%w: line %s quantity %d", ErrBadState, l.SKU, l.Quantity)
		}
		o.lines = append(o.lines, line{sku: l.SKU, quantity: l.Quantity, unitPrice: l.UnitPriceMinor})
	}
	return o, nil
}

سه راهبرد Laravel حیاتی ​

به زبان ساده: در Laravel بین این‌ها انتخاب می‌کنید: مدل Eloquent خودش aggregate باشد، Eloquent را به یک کلاس خالص نگاشت کنید، یا Eloquent را کنار بگذارید و ردیف‌های query builder را نگاشت کنید.

بدفهمی رایج: «DDD در Laravel یعنی دور هر مدل Eloquent یک رابط repository بپیچیم.» repositoryای که مدل Eloquent برمی‌گرداند و save() را عمومی می‌گذارد همان مدل با یک لایهٔ غیرمستقیم اضافه است. انتخاب صادقانه برای هر context و بر اساس تعداد invariantهای واقعی است.

تعریف:

1 Eloquent IS the aggregate2 Repository maps Eloquent3 Repository on query builderOrder extends ModelOrder::with('lines')->find($id)save() is public on the aggregate+ least code, relations free- persistence API leaks, no pure unit test- discipline, not compiler, guards itOrderRecord (Eloquent) + Order (pure)toDomain() / snapshot() in one classEloquent never leaves the repository+ pure domain, fake-able, same tables- mapping code to write and test- two classes per tableDB::table() + array rowshand-written hydrate()explicit SQL, version in WHERE+ no hidden queries or events- most code, no relations helper+ closest to Go/sqlc styleorders · order_lines · outbox (same schema, same transaction rules)
پرسش۱. Eloquent خودِ aggregate۲. Repository، Eloquent را به دامنه نگاشت می‌کند۳. Repository روی query builder
کلاس دامنهApp\Sales\EloquentAggregate\Order extends ModelApp\Sales\Domain\Order (PHP خالص)App\Sales\Domain\Order (PHP خالص)
کلاس‌های ماندگاریهیچOrderRecord، OrderLineRecord (Eloquent)هیچ
Repositoryهیچ یا finder نازکEloquentOrderRepositoryQueryBuilderOrderRepository
تست واحد بدون دیتابیسخیر (مدل برای save اتصال می‌خواهد)بله، با InMemoryOrderRepositoryبله، با InMemoryOrderRepository
API ماندگاری روی aggregateعمومی: save، update، delete، fillپنهانپنهان
relation و eager loadingرایگان: with('lines')رایگان داخل repositoryquery دوم را خودتان می‌نویسید
قفل خوش‌بینانهبا دست: saveWithVersionداخل saveداخل save
رویدادهای مدل / observerاجرا می‌شوند (می‌توانند غافلگیر کنند)روی record اجرا می‌شوند، نه aggregateهیچ
کد نگاشتهیچtoDomain و savehydrate و save
تیم معمولcontext پرCRUD، تیم کوچکدامنهٔ هسته با invariantهای واقعیمسیر داغ، schema قدیمی، بارگذاری انبوه
هزینهٔ صادقانهانضباط، نه کامپایلر، از قواعد محافظت می‌کنددو کلاس برای هر جدول؛ تست نگاشتبیشترین کد؛ بدون شیرینی relation

قاعدهٔ تصمیم. invariantهایی را بشمارید که بیش از یک ردیف را درگیر می‌کنند (سقف line، جمع، ماشین حالت، «پرداخت‌نشده نباید ارسال شود»). صفر یا یک: گزینهٔ ۱ خوب است، $fillable = [] را نگه دارید و متدهای دامنه اضافه کنید. چندتا: گزینهٔ ۲. یک query که اندازه گرفته‌اید داغ است: گزینهٔ ۳ فقط برای همان repository. ترکیب در هر context عادی است: Catalog (عمومی، CRUD) گزینهٔ ۱؛ Sales (هسته) گزینهٔ ۲.

رفتار Eloquent که به آن تکیه می‌کنید (با مستندات Laravel 13 بررسی شده): isDirty() و getDirty() نشان می‌دهند کدام attributeهای یک مدل از زمان بازیابی عوض شده‌اند؛ DB::transaction(callback, attempts: n) هنگام deadlock دوباره تلاش می‌کند؛ lockForUpdate() و sharedLock() روی query builder هستند؛ RefreshDatabase هر تست را در تراکنش می‌گذارد.

php
<?php

declare(strict_types=1);

namespace App\Sales\Domain;

use DateTimeImmutable;
use DomainException;

/**
 * Aggregate root of the Sales context. State is private; only commands change
 * it, only snapshot()/reconstitute() move it across the persistence boundary.
 */
final class Order
{
    /** @var list<array{sku: string, quantity: int, unit_price_minor: int}> */
    private array $lines = [];

    /** @var list<object> */
    private array $events = [];

    private function __construct(
        private readonly string $id,
        private readonly string $customerId,
        private readonly string $currency,
        private string $status,
        private ?DateTimeImmutable $placedAt,
        private int $version,
    ) {
    }

    /** Factory for a brand-new aggregate (version 0 = never saved). */
    public static function draft(string $id, string $customerId, string $currency): self
    {
        return new self($id, $customerId, $currency, 'draft', null, 0);
    }

    /**
     * Rebuild from stored state: no commands run, no events recorded.
     *
     * @param array{id: string, customer_id: string, currency: string, status: string, placed_at: ?string, version: int, lines: list<array{sku: string, quantity: int, unit_price_minor: int}>} $s
     */
    public static function reconstitute(array $s): self
    {
        if (!in_array($s['status'], ['draft', 'placed', 'paid', 'cancelled'], true)) {
            throw new DomainException("unknown order status {$s['status']}");
        }
        $o = new self(
            $s['id'],
            $s['customer_id'],
            $s['currency'],
            $s['status'],
            $s['placed_at'] === null ? null : new DateTimeImmutable($s['placed_at']),
            $s['version'],
        );
        $o->lines = $s['lines'];

        return $o;
    }

    public function addLine(string $sku, int $quantity, int $unitPriceMinor): void
    {
        if ($this->status !== 'draft') {
            throw new DomainException('only a draft order can be edited');
        }
        if ($quantity < 1) {
            throw new DomainException('quantity must be at least 1');
        }
        foreach ($this->lines as $i => $line) {
            if ($line['sku'] === $sku) {
                $this->lines[$i]['quantity'] += $quantity;

                return;
            }
        }
        $this->lines[] = ['sku' => $sku, 'quantity' => $quantity, 'unit_price_minor' => $unitPriceMinor];
    }

    public function place(DateTimeImmutable $now): void
    {
        if ($this->status !== 'draft') {
            throw new DomainException('only a draft order can be placed');
        }
        if ($this->lines === []) {
            throw new DomainException('an order needs at least one line');
        }
        $this->status = 'placed';
        $this->placedAt = $now;
        $this->events[] = new OrderPlaced($this->id, $this->totalMinor(), $now);
    }

    public function markPaid(): void
    {
        if ($this->status !== 'placed') {
            throw new DomainException('only a placed order can be paid');
        }
        $this->status = 'paid';
    }

    public function totalMinor(): int
    {
        return array_sum(array_map(fn (array $l) => $l['quantity'] * $l['unit_price_minor'], $this->lines));
    }

    public function id(): string { return $this->id; }
    public function customerId(): string { return $this->customerId; }
    public function status(): string { return $this->status; }
    public function placedAt(): ?DateTimeImmutable { return $this->placedAt; }
    public function version(): int { return $this->version; }
    public function lineCount(): int { return count($this->lines); }

    /** Events recorded since the last save; repositories store them. @return list<object> */
    public function pendingEvents(): array { return $this->events; }

    /** Called by repositories after a successful save. */
    public function persisted(int $newVersion): void
    {
        $this->version = $newVersion;
        $this->events = [];
    }

    /** @return array{id: string, customer_id: string, currency: string, status: string, placed_at: ?string, version: int, lines: list<array{sku: string, quantity: int, unit_price_minor: int}>} */
    public function snapshot(): array
    {
        return [
            'id' => $this->id,
            'customer_id' => $this->customerId,
            'currency' => $this->currency,
            'status' => $this->status,
            'placed_at' => $this->placedAt?->format('Y-m-d H:i:s'),
            'version' => $this->version,
            'lines' => $this->lines,
        ];
    }
}

Fake و contract test حیاتی ​

به زبان ساده: repository درون‌حافظه تست دامنه و use case را در میلی‌ثانیه اجرا می‌کند؛ یک مجموعه تست مشترک ثابت می‌کند fake و repository واقعی یک‌جور رفتار می‌کنند.

بدفهمی رایج: «mock کردن رابط repository کافی است.» mock همان را برمی‌گرداند که نوشته‌اید و فقط فراخوانی‌ها را چک می‌کند؛ نمی‌تواند بگوید Save version را بالا می‌برد، Get کپی می‌دهد، یا save کهنه شکست می‌خورد. fake با رفتار واقعی که contract test صادقش نگه دارد می‌تواند.

تعریف: Fake پیاده‌سازی سبک ولی کارا است. Contract test یک تابع تست (Go) یا یک trait (PHP) است که factory یک repository را می‌گیرد و وعده‌های رابط را assert می‌کند؛ هر پیاده‌سازی آن را اجرا می‌کند.

text
     Contract test برای هر پیاده‌سازی
1    repotest.Run(t, memory.New)                          -- همیشه، میلی‌ثانیه
2    repotest.Run(t, postgres.New(pool))                  -- وقتی DATABASE_URL هست؛ expected, not run
3    repotest.Run(t, cache.Wrap(memory.New()))            -- decoratorها هم باید contract را نگه دارند
4    -- هر case شکست‌خوردهٔ fake = fake را درست کنید، نه تست را
case در contractاز چه محافظت می‌کند
Save سپس Get همان state را برمی‌گرداندنگاشت در دو جهت
id ناشناخته ErrNotFound استخطایی که use case به 404 نگاشت می‌کند
Save، version را بالا می‌برد و رویدادها را پاک می‌کندتحویل به outbox
save کهنه ErrConcurrentModification استهمزمانی خوش‌بینانه
کل aggregate ذخیره می‌شود (با lineها)نبود save جزئی
Remove و سپس Get شکست می‌خوردچرخهٔ عمر
FindSatisfying به specificationها جواب می‌دهدترجمهٔ پرس‌وجو
go
// Package repotest holds the contract every sales.OrderRepository must pass.
// The in-memory fake and the Postgres implementation run the SAME function,
// so the fake cannot drift away from the real behaviour.
package repotest

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/repositories/sales"
)

// Factory returns a fresh, empty repository for one test.
type Factory func(t *testing.T) sales.OrderRepository

var t0 = time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC)

func newPlaced(t *testing.T, id sales.OrderID, cust sales.CustomerID, at time.Time) *sales.Order {
	t.Helper()
	o := sales.NewOrder(id, cust, "EUR")
	must(t, o.AddLine("sku-1", 2, 1500))
	must(t, o.AddLine("sku-2", 1, 999))
	must(t, o.Place(at))
	return o
}

func must(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

// Run executes every contract case against repositories built by f.
func Run(t *testing.T, f Factory) {
	ctx := context.Background()

	t.Run("save then get returns the same state", func(t *testing.T) {
		r := f(t)
		o := newPlaced(t, "o-1", "c-1", t0)
		must(t, r.Save(ctx, o))
		got, err := r.Get(ctx, "o-1")
		must(t, err)
		if got.Status() != sales.Placed || got.LineCount() != 2 || got.Total() != o.Total() {
			t.Fatalf("round trip lost state: %+v", got.Snapshot())
		}
		if !got.PlacedAt().Equal(t0) {
			t.Fatalf("placedAt = %v", got.PlacedAt())
		}
	})

	t.Run("get unknown id is ErrNotFound", func(t *testing.T) {
		_, err := f(t).Get(ctx, "nope")
		if !errors.Is(err, sales.ErrNotFound) {
			t.Fatalf("err = %v", err)
		}
	})

	t.Run("save bumps the version and clears events", func(t *testing.T) {
		r := f(t)
		o := newPlaced(t, "o-2", "c-1", t0)
		if len(o.PendingEvents()) != 1 {
			t.Fatal("expected OrderPlaced before save")
		}
		must(t, r.Save(ctx, o))
		if o.Version() != 1 || len(o.PendingEvents()) != 0 {
			t.Fatalf("version=%d events=%d", o.Version(), len(o.PendingEvents()))
		}
	})

	t.Run("stale save fails with ErrConcurrentModification", func(t *testing.T) {
		r := f(t)
		must(t, r.Save(ctx, newPlaced(t, "o-3", "c-1", t0)))
		a, _ := r.Get(ctx, "o-3")
		b, _ := r.Get(ctx, "o-3")
		must(t, a.MarkPaid())
		must(t, r.Save(ctx, a))
		must(t, b.MarkPaid())
		if err := r.Save(ctx, b); !errors.Is(err, sales.ErrConcurrentModification) {
			t.Fatalf("err = %v", err)
		}
	})

	t.Run("the aggregate is saved whole, lines included", func(t *testing.T) {
		r := f(t)
		o := sales.NewOrder("o-4", "c-1", "EUR")
		must(t, o.AddLine("sku-1", 1, 100))
		must(t, r.Save(ctx, o))
		again, _ := r.Get(ctx, "o-4")
		must(t, again.AddLine("sku-9", 3, 50))
		must(t, r.Save(ctx, again))
		final, _ := r.Get(ctx, "o-4")
		if final.LineCount() != 2 || final.Total().Minor != 250 {
			t.Fatalf("lines=%d total=%d", final.LineCount(), final.Total().Minor)
		}
	})

	t.Run("remove deletes the aggregate", func(t *testing.T) {
		r := f(t)
		must(t, r.Save(ctx, newPlaced(t, "o-5", "c-1", t0)))
		must(t, r.Remove(ctx, "o-5"))
		if _, err := r.Get(ctx, "o-5"); !errors.Is(err, sales.ErrNotFound) {
			t.Fatalf("err = %v", err)
		}
		if err := r.Remove(ctx, "o-5"); !errors.Is(err, sales.ErrNotFound) {
			t.Fatalf("second remove err = %v", err)
		}
	})

	t.Run("FindSatisfying answers a domain specification", func(t *testing.T) {
		r := f(t)
		now := t0.Add(72 * time.Hour)
		old := newPlaced(t, "o-6", "c-1", t0)                    // placed 3 days ago, unpaid
		fresh := newPlaced(t, "o-7", "c-1", now.Add(-time.Hour)) // placed an hour ago
		paid := newPlaced(t, "o-8", "c-2", t0)
		must(t, paid.MarkPaid())
		for _, o := range []*sales.Order{old, fresh, paid} {
			must(t, r.Save(ctx, o))
		}
		got, err := r.FindSatisfying(ctx, sales.UnpaidLongerThan(now, 48*time.Hour))
		must(t, err)
		if len(got) != 1 || got[0].ID() != "o-6" {
			t.Fatalf("got %d orders", len(got))
		}
		mixed, err := r.FindSatisfying(ctx, sales.Or(sales.ForCustomer{ID: "c-2"}, sales.Not(sales.InStatus{Status: sales.Paid})))
		must(t, err)
		if len(mixed) != 3 {
			t.Fatalf("or/not: got %d, want 3", len(mixed))
		}
	})
}
go
// Package memory is the in-memory OrderRepository used by unit tests and by
// the contract tests. It stores copies (snapshots), never the live pointer,
// so it behaves like a database: mutating a loaded order changes nothing
// until Save.
package memory

import (
	"context"
	"sort"
	"sync"

	"academy/repositories/sales"
)

// Repository is safe for concurrent use.
type Repository struct {
	mu     sync.Mutex
	rows   map[sales.OrderID]sales.Snapshot
	events []sales.Event // what the outbox table would hold
}

// New returns an empty repository.
func New() *Repository { return &Repository{rows: map[sales.OrderID]sales.Snapshot{}} }

// Stored returns the events saved so far (test helper).
func (r *Repository) Stored() []sales.Event {
	r.mu.Lock()
	defer r.mu.Unlock()
	return append([]sales.Event(nil), r.events...)
}

func (r *Repository) Get(_ context.Context, id sales.OrderID) (*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	s, ok := r.rows[id]
	if !ok {
		return nil, sales.ErrNotFound
	}
	return sales.Reconstitute(clone(s))
}

func (r *Repository) Save(_ context.Context, o *sales.Order) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	stored, exists := r.rows[o.ID()]
	switch {
	case !exists && o.Version() != 0:
		return sales.ErrConcurrentModification // it was removed under us
	case exists && stored.Version != o.Version():
		return sales.ErrConcurrentModification
	}
	snap := o.Snapshot()
	snap.Version = o.Version() + 1
	r.rows[o.ID()] = clone(snap)
	r.events = append(r.events, o.PendingEvents()...)
	o.Persisted(snap.Version)
	return nil
}

func (r *Repository) Remove(_ context.Context, id sales.OrderID) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, ok := r.rows[id]; !ok {
		return sales.ErrNotFound
	}
	delete(r.rows, id)
	return nil
}

func (r *Repository) FindSatisfying(_ context.Context, spec sales.Spec) ([]*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	var out []*sales.Order
	for _, s := range r.rows {
		o, err := sales.Reconstitute(clone(s))
		if err != nil {
			return nil, err
		}
		if spec.IsSatisfiedBy(o) {
			out = append(out, o)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].ID() < out[j].ID() })
	return out, nil
}

func clone(s sales.Snapshot) sales.Snapshot {
	s.Lines = append([]sales.LineSnapshot(nil), s.Lines...)
	return s
}
php
<?php

declare(strict_types=1);

namespace Tests\Sales;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\UnpaidLongerThan;
use DateTimeImmutable;

/**
 * Contract tests as a trait: every repository test class uses it and supplies
 * repository() (in-memory, Eloquent, query builder). A fake that passes a different test
 * suite than the real thing is a lie.
 */
trait OrderRepositoryContract
{
    abstract protected function repository(): OrderRepository;

    private function placed(string $id, string $customer, string $at): Order
    {
        $o = Order::draft($id, $customer, 'EUR');
        $o->addLine('sku-1', 2, 1500);
        $o->addLine('sku-2', 1, 999);
        $o->place(new DateTimeImmutable($at));

        return $o;
    }

    public function test_round_trip_keeps_the_whole_aggregate(): void
    {
        $repo = $this->repository();
        $o = $this->placed('o-1', 'c-1', '2026-11-01 10:00:00');
        $repo->save($o);
        $got = $repo->get('o-1');
        $this->assertSame('placed', $got->status());
        $this->assertSame(2, $got->lineCount());
        $this->assertSame($o->totalMinor(), $got->totalMinor());
    }

    public function test_unknown_id_is_not_found(): void
    {
        $this->expectException(OrderNotFound::class);
        $this->repository()->get('nope');
    }

    public function test_save_bumps_version_and_clears_events(): void
    {
        $repo = $this->repository();
        $o = $this->placed('o-2', 'c-1', '2026-11-01 10:00:00');
        $this->assertCount(1, $o->pendingEvents());
        $repo->save($o);
        $this->assertSame(1, $o->version());
        $this->assertSame([], $o->pendingEvents());
    }

    public function test_stale_save_is_rejected(): void
    {
        $repo = $this->repository();
        $repo->save($this->placed('o-3', 'c-1', '2026-11-01 10:00:00'));
        $a = $repo->get('o-3');
        $b = $repo->get('o-3');
        $a->markPaid();
        $repo->save($a);
        $b->markPaid();
        $this->expectException(ConcurrentModification::class);
        $repo->save($b);
    }

    public function test_remove_then_get_fails(): void
    {
        $repo = $this->repository();
        $repo->save($this->placed('o-4', 'c-1', '2026-11-01 10:00:00'));
        $repo->remove('o-4');
        $this->expectException(OrderNotFound::class);
        $repo->get('o-4');
    }

    public function test_find_satisfying_a_specification(): void
    {
        $repo = $this->repository();
        $now = new DateTimeImmutable('2026-11-04 10:00:00');
        $paid = $this->placed('o-7', 'c-2', '2026-11-01 10:00:00');
        $paid->markPaid();
        $repo->save($this->placed('o-5', 'c-1', '2026-11-01 10:00:00')); // old, unpaid
        $repo->save($this->placed('o-6', 'c-1', '2026-11-04 09:00:00')); // recent
        $repo->save($paid);

        $overdue = $repo->findSatisfying(UnpaidLongerThan::spec($now, 48 * 3600));
        $this->assertSame(['o-5'], array_map(fn (Order $o) => $o->id(), $overdue));
    }
}

کش داخل repository تکمیلی ​

به زبان ساده: کش جلوی Get می‌تواند خواندن را ارزان کند، ولی نباید بگذارد بی‌خبر از نسخهٔ کهنه ذخیره کنید.

بدفهمی رایج: «کش کردن aggregate سرعت مجانی است.» aggregate کش‌شده یک کپی است؛ اگر دو request یک شیء زندهٔ مشترک را بگیرند state هم را خراب می‌کنند و داده کهنه دستورها را تغذیه می‌کند. snapshot را کش کنید، هر بار نمونهٔ تازه بدهید، با Save/Remove باطل کنید، و بررسی version را به‌عنوان تور ایمنی نگه دارید.

تعریف: کش را به‌صورت decorator پیاده کنید که همان رابط را پیاده می‌کند، فقط Get را کش می‌کند و هنگام نوشتن باطل می‌کند. با بررسی version، خواندن کهنه حداکثر یک ErrConcurrentModification هزینه دارد. FindSatisfying را برای دستورها کش نکنید. لایه‌های کش را در Storage & Data Scaling و Redis ببینید.

قاعدهدلیل
snapshot را کش کنید، نه aggregate زنده رافراخوان‌ها آنچه می‌گیرند تغییر می‌دهند
قبل و بعد از Save باطل کنیدsave شکست‌خورده نباید ورودی کهنه بگذارد
هنگام Remove باطل کنیدوگرنه سفارش حذف‌شده سرو می‌شود
بررسی version را نگه داریدکهنگی را به retry تبدیل می‌کند، نه خرابی
TTL به‌عنوان پشتیباناستقرار چندنمونه‌ای نمی‌تواند همدیگر را باطل کند
اینجا برای صفحه‌های خواندنی کش نکنیدصفحه‌ها read model با کش خودش دارند
go
// Package cache is a read-through decorator for the Order repository.
// It caches Get only, and drops the entry on every Save/Remove, so a stale
// copy can at worst cause one ErrConcurrentModification, never a lost update.
package cache

import (
	"context"
	"sync"

	"academy/repositories/sales"
)

// Repository wraps another OrderRepository.
type Repository struct {
	sales.OrderRepository
	mu    sync.Mutex
	items map[sales.OrderID]sales.Snapshot
}

// Wrap returns the caching decorator.
func Wrap(inner sales.OrderRepository) *Repository {
	return &Repository{OrderRepository: inner, items: map[sales.OrderID]sales.Snapshot{}}
}

func (r *Repository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	r.mu.Lock()
	s, ok := r.items[id]
	r.mu.Unlock()
	if ok {
		return sales.Reconstitute(s) // a fresh instance every time: never share the live aggregate
	}
	o, err := r.OrderRepository.Get(ctx, id)
	if err != nil {
		return nil, err
	}
	r.mu.Lock()
	r.items[id] = o.Snapshot()
	r.mu.Unlock()
	return o, nil
}

func (r *Repository) Save(ctx context.Context, o *sales.Order) error {
	r.forget(o.ID()) // invalidate before AND after: a failed save must not leave a stale entry
	err := r.OrderRepository.Save(ctx, o)
	r.forget(o.ID())
	return err
}

func (r *Repository) Remove(ctx context.Context, id sales.OrderID) error {
	r.forget(id)
	err := r.OrderRepository.Remove(ctx, id)
	r.forget(id)
	return err
}

func (r *Repository) forget(id sales.OrderID) {
	r.mu.Lock()
	delete(r.items, id)
	r.mu.Unlock()
}

انتشار رویداد هنگام ذخیره مهم ​

به زبان ساده: aggregate آنچه رخ داده را به خاطر می‌سپارد؛ repository این حقایق را کنار state ذخیره می‌کند؛ یک relay بعداً منتشرشان می‌کند.

بدفهمی رایج: «Save باید رویداد را به broker منتشر کند.» فراخوانی broker داخل تراکنش ممکن است موفق شود ولی commit شکست بخورد (رویداد شبح)، یا commit موفق شود و انتشار شکست بخورد (رویداد گم‌شده). بعد از commit از یک رکورد ذخیره‌شده منتشر کنید. این همان Outbox Pattern است.

تعریف: aggregate هنگام اجرای دستورها رویداد اضافه می‌کند (o.events = append(...)). Save ردیف state و به‌ازای هر رویداد یک ردیف outbox را در همان تراکنش می‌نویسد، سپس Persisted(newVersion) را صدا می‌زند که فهرست در انتظار را پاک می‌کند. یک relay (polling یا CDC، نگاه کنید Change Data Capture) outbox را منتشر می‌کند. مصرف‌کننده‌ها باید idempotent باشند (Idempotent Consumer & Inbox). جدایی domain event و integration event در آن فصل است.

رویکردبا state اتمیک است؟هزینه
انتشار داخل Saveخیررویداد شبح یا گم‌شده
انتشار در سرویس برنامه بعد از Saveخیراگر process بین این دو بمیرد رویداد گم می‌شود
ارسال رویداد Laravel بعد از commit (afterCommit)فقط در یک processبا crash گم می‌شود؛ برای listenerهای درون‌process خوب است
ردیف outbox در Save + relayبلهیک جدول و یک process relay
Event sourcing (رویدادها خودِ state هستند)بلهمدل متفاوت؛ Event Sourcing & CQRS

ضدالگوها مهم ​

به زبان ساده: فروپاشی repository تدریجی است: یک متد دیگر، یک Where دیگر، تا تبدیل به دروازهٔ جدول شود.

بدفهمی رایج: «Repository<T> عمومی boilerplate را حذف می‌کند پس طراحی خوبی است.» آن بخشی را حذف می‌کند که باید برای هر aggregate فرق کند (finderها، قواعد بارگذاری، معنای تراکنش) و بخشی را نگه می‌دارد که نباید وجود داشته باشد (پرس‌وجوی عمومی روی فیلد).

تعریف و درمان:

ضدالگونشانهچرا آسیب می‌زنددرمان
Repository<T> عمومی با ۳۰ متدGetAll، Where، Paginate، Raw روی هر نوعمعنای aggregate ندارد؛ DAO می‌شودیک رابط کوچک برای هر ریشه
Repository برای entity فرزندOrderLineRepository.UpdateQuantityریشه را دور می‌زند پس سقف line و جمع نادیده می‌ماندفقط Order repository دارد؛ lineها با Order.AddLine عوض می‌شوند
نشت Builder / Queryrepo.Query() یک Builder الکوئنت یا *sql.Rows می‌دهدفراخوان‌ها SQL می‌نویسند؛ تغییر ذخیره‌سازی همه را می‌شکندaggregate یا DTO برگردانید؛ finder نام‌دار بیفزایید
«Repository» که DAO روی جدول استیک کلاس برای هر جدول، فقط CRUDaggregate روی چهار کلاس پخش، بدون invariantرابط به شکل aggregate
منطق کسب‌وکار در repositoryif order.Total > limit داخل Saveقاعده‌ها از تست دامنه پنهان می‌ماندبه aggregate یا domain service ببرید
Repository commit می‌کندtx.Commit() داخل Saveuse case اتمیک بودن را از دست می‌دهدسرویس برنامه مالک تراکنش است
Repository aggregate نیمه‌بارشده می‌دهدlineها تا لمس نشوند nilinvariantها روی state ناقص بررسی می‌شوندکامل بارگذاری کنید، یا proxy تنبل که کامل رفتار کند
Repository context دیگر را صدا می‌زندSalesOrderRepository از catalog_products می‌خوانداتصال بین contextهاCatalog API یا کپی خواندنی محلی
Active Record پنهانمتد دامنه save() صدا می‌زنددامنه به ماندگاری وابسته استrepository ذخیره می‌کند، aggregate هرگز
Save از هر جاcontrollerها $repo->save() می‌زنندinvariantها نادیده می‌مانندسرویس برنامه تنها فراخوان است
go
// Package wrong shows the repository anti-patterns. Do not copy.
package wrong

import "context"

// Repository is the "one generic repository for everything" trap. Thirty
// methods later it is a DAO: it knows every table and enforces no invariant.
type Repository[T any] interface {
	GetByID(ctx context.Context, id string) (T, error)
	GetAll(ctx context.Context) ([]T, error)
	Create(ctx context.Context, e T) error
	Update(ctx context.Context, e T) error
	Delete(ctx context.Context, id string) error
	FindBy(ctx context.Context, field string, value any) ([]T, error)
	// ... Count, Exists, Paginate, Where(...), Raw(sql string, args ...any) ...
}

// OrderLineRepository is wrong in a different way: OrderLine is not an
// aggregate root. Saving lines on their own bypasses Order's invariants
// (line limit, status checks, total).
type OrderLineRepository interface {
	Create(ctx context.Context, orderID string, sku string, qty int) error
	UpdateQuantity(ctx context.Context, orderID string, sku string, qty int) error
}

// QueryLeak returns the persistence tool itself, so every caller now depends
// on the SQL dialect and the table layout.
type QueryLeak interface {
	Query(ctx context.Context) (queryBuilder any)
}
php
<?php

declare(strict_types=1);

namespace App\Wrong;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Anti-pattern: one "repository" for every model. It is a DAO over tables:
 * it enforces no invariant, leaks Builder, and invites Order::lines updates
 * that bypass the Order root.
 *
 * @template T of Model
 */
abstract class GenericRepository
{
    /** @return class-string<T> */
    abstract protected function model(): string;

    public function find(int|string $id): ?Model { return $this->model()::find($id); }
    public function all(): iterable { return $this->model()::all(); }
    public function create(array $attrs): Model { return $this->model()::create($attrs); }
    public function update(int|string $id, array $attrs): bool { return $this->model()::whereKey($id)->update($attrs) > 0; }
    public function delete(int|string $id): bool { return $this->model()::destroy($id) > 0; }

    // The leak: every caller now writes Eloquent queries (and filters,
    // joins and raw SQL) against the persistence model.
    public function query(): Builder { return $this->model()::query(); }
}

سازوکار (Mechanics) ​

Save قدم‌به‌قدم حیاتی ​

text
     Save(ctx, order)          -- داخل تراکنش سرویس برنامه
1    snapshot := order.Snapshot()
2    version == 0 ?  INSERT INTO orders (..., version) VALUES (..., 1)      -- unique_violation 23505 -> conflict
3    version  > 0 ?  UPDATE orders SET ..., version = version + 1 WHERE id = $1 AND version = $loaded
4                    rows affected = 0 -> ErrConcurrentModification
5    DELETE FROM order_lines WHERE order_id = $1; INSERT each line          -- جایگزینی فرزندان
6    INSERT INTO outbox (topic, payload) برای هر رویداد در انتظار
7    order.Persisted(version + 1)  -- فقط حالا: version جدید، رویدادها پاک
دغدغهجزئیات
جایگزینی در برابر diff فرزندانجایگزینی ساده است و زیر حدود ۱۰۰ line خوب؛ وقتی line کلید خارجی یا تاریخچه دارد diff کنید
نقض uniquePostgreSQL SQLSTATE 23505؛ MySQL خطای 1062؛ هر دو یعنی دیگری زودتر id را درج کرده
شکست serialisation40001 زیر REPEATABLE READ یا SERIALIZABLE: تراکنش را دوباره اجرا کنید، Isolation Levels
Deadlock40P01 (PostgreSQL)، 1213 (MySQL): retry؛ DB::transaction(..., attempts: n) در Laravel این را انجام می‌دهد
انتظار قفلMySQL 1205؛ PostgreSQL با lock_timeout خطای 55P03 می‌دهد
cascade کلید خارجیON DELETE CASCADE روی order_lines Remove را یک دستور می‌کند

Get قدم‌به‌قدم حیاتی ​

text
     Get(ctx, id)
1    SELECT ... FROM orders WHERE id = $1                    -- 0 rows -> ErrNotFound
2    SELECT ... FROM order_lines WHERE order_id = ANY($1)    -- یک query برای همهٔ lineها
3    Reconstitute(snapshot)                                  -- اعتبارسنجی؛ بدون رویداد
4    return *Order (نمونهٔ تازه، version = مقدار ذخیره‌شده)

FindSatisfying چندین aggregate را با دو query می‌آورد (orders، سپس همهٔ lineها با = ANY($1::text[]) یا whereIn) نه یک query برای هر سفارش. این دفاع repository در برابر مشکل N+1 است که در ORM Pitfalls آمده.

sqlc و pgx در Go مهم ​

ابزارچیستنقش در repository
pgx (github.com/jackc/pgx/v5)درایور و جعبه‌ابزار PostgreSQLpgx.Tx، pgxpool.Pool، Exec، Query، QueryRow
sqlcاز فایل SQL کد Go ایمن از نظر نوع تولید می‌کندیک متد تولیدی برای هر query؛ رابط DBTX با pool یا tx کار می‌کند؛ WithTx
GORMORMdb.Transaction(func(tx *gorm.DB) error)؛ تراکنش پیش‌فرض نوشتن را می‌شود با SkipDefaultTransaction خاموش کرد
entفریم‌ورک entity با codegenclient.Tx(ctx)، tx.Client() برای client تراکنشی
database/sqlکتابخانهٔ استانداردdb.BeginTx، tx.ExecContext

README ـِ sqlc آن را در سه قدم توصیف می‌کند: query را به SQL می‌نویسید، sqlc را اجرا می‌کنید تا کد با رابط‌های ایمن از نظر نوع تولید شود، و کد برنامه را روی کد تولیدی می‌نویسید. ما فایل query را در postgres/queries.sql نگه می‌داریم و یک DBTX دست‌نویس با همان شکل، چون sqlc در این build نصب نیست؛ در هر صورت contract test تور ایمنی است.

sql
-- sqlc input (sqlc.yaml: engine postgresql, sql_package pgx/v5). sqlc would
-- generate a Queries struct with one typed method per query below and a
-- DBTX interface; repository.go uses the same shape written by hand so this
-- module compiles without running the generator.

-- name: GetOrder :one
SELECT id, customer_id, currency, status, placed_at, version
FROM orders WHERE id = $1;

-- name: ListLinesForOrders :many
SELECT order_id, sku, quantity, unit_price_minor
FROM order_lines WHERE order_id = ANY($1::text[]) ORDER BY order_id, sku;

-- name: InsertOrder :exec
INSERT INTO orders (id, customer_id, currency, status, placed_at, version)
VALUES ($1, $2, $3, $4, $5, 1);

-- name: UpdateOrder :execrows
UPDATE orders
SET customer_id = $2, currency = $3, status = $4, placed_at = $5, version = version + 1
WHERE id = $1 AND version = $6;

-- name: DeleteLines :exec
DELETE FROM order_lines WHERE order_id = $1;

-- name: InsertLine :exec
INSERT INTO order_lines (order_id, sku, quantity, unit_price_minor) VALUES ($1, $2, $3, $4);

-- name: InsertOutbox :exec
INSERT INTO outbox (topic, payload) VALUES ($1, $2);

-- name: DeleteOrder :execrows
DELETE FROM orders WHERE id = $1;

Go ​

ماژول Go به نام academy/repositories کل مثال را دارد. همه‌چیز جز تست یکپارچگی Postgres بدون دیتابیس اجرا می‌شود: go vet ./... && go test ./....

aggregate و snapshot آن ​

go
// Package sales is the Sales bounded context. Order is the aggregate root;
// the repository in this chapter loads and saves it as one unit.
package sales

import (
	"errors"
	"fmt"
	"time"
)

type (
	// OrderID is the identity of the Order aggregate.
	OrderID string
	// CustomerID references the Identity context's customer by id only.
	CustomerID string
	// SKU references a Catalog product by id only.
	SKU string
)

// Status is the order state machine.
type Status string

const (
	Draft     Status = "draft"
	Placed    Status = "placed"
	Paid      Status = "paid"
	Cancelled Status = "cancelled"
)

var (
	ErrNotEditable = errors.New("only a draft order can be edited")
	ErrEmptyOrder  = errors.New("an order needs at least one line")
	ErrBadQuantity = errors.New("quantity must be at least 1")
	ErrBadStatus   = errors.New("unknown order status")
	ErrBadState    = errors.New("stored state violates an order invariant")
)

// Money is a value object in minor units.
type Money struct {
	Minor    int64
	Currency string
}

type line struct {
	sku       SKU
	quantity  int
	unitPrice int64
}

// Order is the aggregate root. All fields are private: only the root's
// methods change state, only Snapshot/Reconstitute move state across the
// persistence boundary.
type Order struct {
	id       OrderID
	customer CustomerID
	currency string
	status   Status
	lines    []line
	placedAt time.Time
	version  int // optimistic concurrency token; 0 means "never saved"
	events   []Event
}

// NewOrder starts a draft order (the factory for a brand-new aggregate).
func NewOrder(id OrderID, customer CustomerID, currency string) *Order {
	return &Order{id: id, customer: customer, currency: currency, status: Draft}
}

// AddLine adds or merges a line while the order is a draft.
func (o *Order) AddLine(sku SKU, qty int, unitPriceMinor int64) error {
	if o.status != Draft {
		return ErrNotEditable
	}
	if qty < 1 {
		return ErrBadQuantity
	}
	for i := range o.lines {
		if o.lines[i].sku == sku {
			o.lines[i].quantity += qty
			return nil
		}
	}
	o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: unitPriceMinor})
	return nil
}

// Place commits the order and records OrderPlaced for the outbox.
func (o *Order) Place(now time.Time) error {
	if o.status != Draft {
		return fmt.Errorf("place: %w", ErrNotEditable)
	}
	if len(o.lines) == 0 {
		return ErrEmptyOrder
	}
	o.status = Placed
	o.placedAt = now
	o.events = append(o.events, OrderPlaced{OrderID: o.id, Total: o.Total(), At: now})
	return nil
}

// MarkPaid is called when Billing reports a captured payment.
func (o *Order) MarkPaid() error {
	if o.status != Placed {
		return errors.New("only a placed order can be paid")
	}
	o.status = Paid
	return nil
}

// Total is derived from the lines.
func (o *Order) Total() Money {
	var t int64
	for _, l := range o.lines {
		t += l.unitPrice * int64(l.quantity)
	}
	return Money{Minor: t, Currency: o.currency}
}

func (o *Order) ID() OrderID            { return o.id }
func (o *Order) Customer() CustomerID   { return o.customer }
func (o *Order) Status() Status         { return o.status }
func (o *Order) Version() int           { return o.version }
func (o *Order) PlacedAt() time.Time    { return o.placedAt }
func (o *Order) LineCount() int         { return len(o.lines) }
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }

// Persisted is called by repository implementations after a successful save:
// it records the new version and clears the events the repository has stored.
func (o *Order) Persisted(newVersion int) {
	o.version = newVersion
	o.events = nil
}

// LineSnapshot is the flat state of one line.
type LineSnapshot struct {
	SKU            SKU
	Quantity       int
	UnitPriceMinor int64
}

// Snapshot is the flat, exported state of the whole aggregate. It is the
// shape that crosses the persistence boundary in both directions.
type Snapshot struct {
	ID       OrderID
	Customer CustomerID
	Currency string
	Status   Status
	Lines    []LineSnapshot
	PlacedAt time.Time
	Version  int
}

// Snapshot copies the state out (a memento). It never exposes internal slices.
func (o *Order) Snapshot() Snapshot {
	s := Snapshot{ID: o.id, Customer: o.customer, Currency: o.currency, Status: o.status,
		PlacedAt: o.placedAt, Version: o.version}
	for _, l := range o.lines {
		s.Lines = append(s.Lines, LineSnapshot{SKU: l.sku, Quantity: l.quantity, UnitPriceMinor: l.unitPrice})
	}
	return s
}

// Reconstitute rebuilds an aggregate from stored state. It runs no commands,
// records no events, and re-checks only what a corrupt row could break.
func Reconstitute(s Snapshot) (*Order, error) {
	switch s.Status {
	case Draft, Placed, Paid, Cancelled:
	default:
		return nil, fmt.Errorf("%w: %q", ErrBadStatus, s.Status)
	}
	if s.Status != Draft && len(s.Lines) == 0 {
		return nil, fmt.Errorf("%w: %s has no lines", ErrBadState, s.ID)
	}
	o := &Order{id: s.ID, customer: s.Customer, currency: s.Currency, status: s.Status,
		placedAt: s.PlacedAt, version: s.Version}
	for _, l := range s.Lines {
		if l.Quantity < 1 {
			return nil, fmt.Errorf("%w: line %s quantity %d", ErrBadState, l.SKU, l.Quantity)
		}
		o.lines = append(o.lines, line{sku: l.SKU, quantity: l.Quantity, unitPrice: l.UnitPriceMinor})
	}
	return o, nil
}

رابط در دامنه می‌نشیند ​

go
package sales

import (
	"context"
	"errors"
)

var (
	// ErrNotFound means no aggregate has this identity.
	ErrNotFound = errors.New("order not found")
	// ErrConcurrentModification means the stored version moved since we loaded
	// the aggregate. Reload, re-run the command, save again.
	ErrConcurrentModification = errors.New("order was modified concurrently")
)

// OrderRepository is the persistence-oriented repository of the Order
// aggregate. One interface per aggregate root; no LineRepository exists.
// It lives in the domain package; implementations live in infrastructure.
type OrderRepository interface {
	// Get loads the whole aggregate or returns ErrNotFound.
	Get(ctx context.Context, id OrderID) (*Order, error)
	// Save stores the whole aggregate and its pending events. A new aggregate
	// (Version 0) is inserted; an existing one is updated only if the stored
	// version still equals o.Version(), otherwise ErrConcurrentModification.
	// Save never commits a transaction the caller opened.
	Save(ctx context.Context, o *Order) error
	// Remove deletes the aggregate and everything inside it.
	Remove(ctx context.Context, id OrderID) error
	// FindSatisfying returns aggregates matching a domain specification.
	FindSatisfying(ctx context.Context, spec Spec) ([]*Order, error)
}

دو پیاده‌سازی، یک contract ​

go
// Package memory is the in-memory OrderRepository used by unit tests and by
// the contract tests. It stores copies (snapshots), never the live pointer,
// so it behaves like a database: mutating a loaded order changes nothing
// until Save.
package memory

import (
	"context"
	"sort"
	"sync"

	"academy/repositories/sales"
)

// Repository is safe for concurrent use.
type Repository struct {
	mu     sync.Mutex
	rows   map[sales.OrderID]sales.Snapshot
	events []sales.Event // what the outbox table would hold
}

// New returns an empty repository.
func New() *Repository { return &Repository{rows: map[sales.OrderID]sales.Snapshot{}} }

// Stored returns the events saved so far (test helper).
func (r *Repository) Stored() []sales.Event {
	r.mu.Lock()
	defer r.mu.Unlock()
	return append([]sales.Event(nil), r.events...)
}

func (r *Repository) Get(_ context.Context, id sales.OrderID) (*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	s, ok := r.rows[id]
	if !ok {
		return nil, sales.ErrNotFound
	}
	return sales.Reconstitute(clone(s))
}

func (r *Repository) Save(_ context.Context, o *sales.Order) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	stored, exists := r.rows[o.ID()]
	switch {
	case !exists && o.Version() != 0:
		return sales.ErrConcurrentModification // it was removed under us
	case exists && stored.Version != o.Version():
		return sales.ErrConcurrentModification
	}
	snap := o.Snapshot()
	snap.Version = o.Version() + 1
	r.rows[o.ID()] = clone(snap)
	r.events = append(r.events, o.PendingEvents()...)
	o.Persisted(snap.Version)
	return nil
}

func (r *Repository) Remove(_ context.Context, id sales.OrderID) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, ok := r.rows[id]; !ok {
		return sales.ErrNotFound
	}
	delete(r.rows, id)
	return nil
}

func (r *Repository) FindSatisfying(_ context.Context, spec sales.Spec) ([]*sales.Order, error) {
	r.mu.Lock()
	defer r.mu.Unlock()
	var out []*sales.Order
	for _, s := range r.rows {
		o, err := sales.Reconstitute(clone(s))
		if err != nil {
			return nil, err
		}
		if spec.IsSatisfiedBy(o) {
			out = append(out, o)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].ID() < out[j].ID() })
	return out, nil
}

func clone(s sales.Snapshot) sales.Snapshot {
	s.Lines = append([]sales.LineSnapshot(nil), s.Lines...)
	return s
}
go
// Package postgres implements sales.OrderRepository with pgx. The repository
// never commits a transaction it did not start: if the caller put a pgx.Tx in
// the context (see UnitOfWork), every statement joins it; otherwise Save opens
// and commits its own short transaction.
package postgres

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"

	"academy/repositories/sales"
)

// DBTX is satisfied by *pgxpool.Pool and pgx.Tx; sqlc generates the same
// interface, which is why sqlc code works inside and outside a transaction.
type DBTX interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

type txKey struct{}

// UnitOfWork runs fn in one transaction; repositories called with the ctx it
// passes join that transaction. This is the application layer's tool: the
// repository itself has no Begin/Commit.
type UnitOfWork struct{ Pool *pgxpool.Pool }

// Do begins a transaction, runs fn, commits on nil and rolls back on error.
func (u UnitOfWork) Do(ctx context.Context, fn func(ctx context.Context) error) error {
	tx, err := u.Pool.Begin(ctx)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback(ctx) }() // no-op after Commit
	if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
		return err
	}
	return tx.Commit(ctx)
}

// Repository is the Postgres implementation.
type Repository struct{ pool *pgxpool.Pool }

// New returns a repository on the pool.
func New(pool *pgxpool.Pool) *Repository { return &Repository{pool: pool} }

func (r *Repository) db(ctx context.Context) DBTX {
	if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
		return tx
	}
	return r.pool
}

func (r *Repository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
	db := r.db(ctx)
	var s sales.Snapshot
	var placed *time.Time
	err := db.QueryRow(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE id = $1`, string(id)).
		Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version)
	if errors.Is(err, pgx.ErrNoRows) {
		return nil, sales.ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	if placed != nil {
		s.PlacedAt = *placed
	}
	lines, err := r.lines(ctx, db, []string{string(id)})
	if err != nil {
		return nil, err
	}
	s.Lines = lines[id]
	return sales.Reconstitute(s)
}

func (r *Repository) lines(ctx context.Context, db DBTX, ids []string) (map[sales.OrderID][]sales.LineSnapshot, error) {
	rows, err := db.Query(ctx, `SELECT order_id, sku, quantity, unit_price_minor FROM order_lines WHERE order_id = ANY($1::text[]) ORDER BY order_id, sku`, ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[sales.OrderID][]sales.LineSnapshot{}
	for rows.Next() {
		var oid sales.OrderID
		var l sales.LineSnapshot
		if err := rows.Scan(&oid, &l.SKU, &l.Quantity, &l.UnitPriceMinor); err != nil {
			return nil, err
		}
		out[oid] = append(out[oid], l)
	}
	return out, rows.Err()
}

func (r *Repository) Save(ctx context.Context, o *sales.Order) error {
	if _, inTx := ctx.Value(txKey{}).(pgx.Tx); !inTx {
		// Standalone call: open our own short transaction and join it.
		return UnitOfWork{Pool: r.pool}.Do(ctx, func(ctx context.Context) error { return r.Save(ctx, o) })
	}
	db := r.db(ctx)
	s := o.Snapshot()
	var placed *time.Time
	if !s.PlacedAt.IsZero() {
		placed = &s.PlacedAt
	}
	next := s.Version + 1
	if s.Version == 0 {
		_, err := db.Exec(ctx, `INSERT INTO orders (id, customer_id, currency, status, placed_at, version) VALUES ($1,$2,$3,$4,$5,1)`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed)
		var pgErr *pgconn.PgError
		if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation: someone inserted the same id
			return sales.ErrConcurrentModification
		}
		if err != nil {
			return err
		}
	} else {
		tag, err := db.Exec(ctx, `UPDATE orders SET customer_id=$2, currency=$3, status=$4, placed_at=$5, version=version+1 WHERE id=$1 AND version=$6`,
			string(s.ID), string(s.Customer), s.Currency, string(s.Status), placed, s.Version)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 { // stale version, or the row is gone
			return sales.ErrConcurrentModification
		}
	}
	// The aggregate is stored whole: replace its internal rows.
	if _, err := db.Exec(ctx, `DELETE FROM order_lines WHERE order_id = $1`, string(s.ID)); err != nil {
		return err
	}
	for _, l := range s.Lines {
		if _, err := db.Exec(ctx, `INSERT INTO order_lines (order_id, sku, quantity, unit_price_minor) VALUES ($1,$2,$3,$4)`,
			string(s.ID), string(l.SKU), l.Quantity, l.UnitPriceMinor); err != nil {
			return err
		}
	}
	// Events go to the outbox in the same transaction (no broker call here).
	for _, e := range o.PendingEvents() {
		topic, ok := outboxTopics[e.EventName()]
		if !ok {
			return fmt.Errorf("no published topic for %s", e.EventName())
		}
		payload, err := json.Marshal(e)
		if err != nil {
			return err
		}
		if _, err := db.Exec(ctx, `INSERT INTO outbox (topic, payload) VALUES ($1, $2)`, topic, payload); err != nil {
			return err
		}
	}
	o.Persisted(next) // only after every statement succeeded
	return nil
}

// outboxTopics maps domain event class names to the dotted, versioned topic
// of the published language. Only the outbox row carries the wire name.
var outboxTopics = map[string]string{
	"OrderPlaced": "sales.order.placed.v1",
}

func (r *Repository) Remove(ctx context.Context, id sales.OrderID) error {
	tag, err := r.db(ctx).Exec(ctx, `DELETE FROM orders WHERE id = $1`, string(id)) // lines go by ON DELETE CASCADE
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return sales.ErrNotFound
	}
	return nil
}

func (r *Repository) FindSatisfying(ctx context.Context, spec sales.Spec) ([]*sales.Order, error) {
	where, args, err := toSQL(spec, 1)
	if err != nil {
		return nil, err
	}
	db := r.db(ctx)
	rows, err := db.Query(ctx, `SELECT id, customer_id, currency, status, placed_at, version FROM orders WHERE `+where+` ORDER BY id`, args...)
	if err != nil {
		return nil, err
	}
	var snaps []sales.Snapshot
	var ids []string
	for rows.Next() {
		var s sales.Snapshot
		var placed *time.Time
		if err := rows.Scan(&s.ID, &s.Customer, &s.Currency, &s.Status, &placed, &s.Version); err != nil {
			rows.Close()
			return nil, err
		}
		if placed != nil {
			s.PlacedAt = *placed
		}
		snaps = append(snaps, s)
		ids = append(ids, string(s.ID))
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return nil, err
	}
	if len(snaps) == 0 {
		return nil, nil
	}
	lines, err := r.lines(ctx, db, ids) // one query for all lines, not one per order
	if err != nil {
		return nil, err
	}
	out := make([]*sales.Order, 0, len(snaps))
	for _, s := range snaps {
		s.Lines = lines[s.ID]
		o, err := sales.Reconstitute(s)
		if err != nil {
			return nil, fmt.Errorf("order %s: %w", s.ID, err)
		}
		out = append(out, o)
	}
	return out, nil
}
sql
CREATE TABLE orders (
    id          text        PRIMARY KEY,
    customer_id text        NOT NULL,
    currency    char(3)     NOT NULL,
    status      text        NOT NULL CHECK (status IN ('draft','placed','paid','cancelled')),
    placed_at   timestamptz,
    version     integer     NOT NULL DEFAULT 1
);
CREATE TABLE order_lines (
    order_id         text    NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    sku              text    NOT NULL,
    quantity         integer NOT NULL CHECK (quantity >= 1),
    unit_price_minor bigint  NOT NULL,
    PRIMARY KEY (order_id, sku)
);
-- Written in the SAME transaction as the aggregate (see the outbox chapter).
CREATE TABLE outbox (
    id         bigserial   PRIMARY KEY,
    topic      text        NOT NULL,
    payload    jsonb       NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_status_placed_at ON orders (status, placed_at);
CREATE INDEX orders_customer ON orders (customer_id);
go
package memory_test

import (
	"testing"

	"academy/repositories/memory"
	"academy/repositories/repotest"
	"academy/repositories/sales"
)

// The same contract the Postgres repository must pass.
func TestMemoryRepositoryContract(t *testing.T) {
	repotest.Run(t, func(t *testing.T) sales.OrderRepository { return memory.New() })
}
go
package postgres_test

import (
	"context"
	"os"
	"testing"

	"github.com/jackc/pgx/v5/pgxpool"

	"academy/repositories/postgres"
	"academy/repositories/repotest"
	"academy/repositories/sales"
)

// Runs only when DATABASE_URL points at a Postgres that already has
// schema.sql applied. Expected, not run in this chapter's build.
func TestPostgresRepositoryContract(t *testing.T) {
	url := os.Getenv("DATABASE_URL")
	if url == "" {
		t.Skip("DATABASE_URL not set")
	}
	pool, err := pgxpool.New(context.Background(), url)
	if err != nil {
		t.Fatal(err)
	}
	defer pool.Close()
	repotest.Run(t, func(t *testing.T) sales.OrderRepository {
		if _, err := pool.Exec(context.Background(), `TRUNCATE orders, outbox CASCADE`); err != nil {
			t.Fatal(err)
		}
		return postgres.New(pool)
	})
}

تست واحد یک use case بدون دیتابیس ​

go
package app_test

import (
	"context"
	"testing"
	"time"

	"academy/repositories/app"
	"academy/repositories/memory"
	"academy/repositories/sales"
)

// passthrough is a fake Tx: unit tests of the use case need no database.
type passthrough struct{}

func (passthrough) Do(ctx context.Context, fn func(context.Context) error) error { return fn(ctx) }

func TestPlaceOrderSavesAndRecordsEvent(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	o := sales.NewOrder("o-1", "c-1", "EUR")
	_ = o.AddLine("s", 1, 100)
	_ = repo.Save(ctx, o)

	h := app.PlaceOrder{Tx: passthrough{}, Orders: repo, Now: func() time.Time { return time.Unix(0, 0) }}
	if err := h.Handle(ctx, "o-1"); err != nil {
		t.Fatal(err)
	}
	got, _ := repo.Get(ctx, "o-1")
	if got.Status() != sales.Placed {
		t.Fatalf("status = %s", got.Status())
	}
	if len(repo.Stored()) != 1 {
		t.Fatalf("stored events = %d", len(repo.Stored()))
	}
}

func TestPlaceOrderTwiceFailsInTheDomain(t *testing.T) {
	ctx := context.Background()
	repo := memory.New()
	o := sales.NewOrder("o-1", "c-1", "EUR")
	_ = o.AddLine("s", 1, 100)
	_ = repo.Save(ctx, o)
	h := app.PlaceOrder{Tx: passthrough{}, Orders: repo, Now: time.Now}
	if err := h.Handle(ctx, "o-1"); err != nil {
		t.Fatal(err)
	}
	if err := h.Handle(ctx, "o-1"); err == nil {
		t.Fatal("second place must fail")
	}
}

زاویهٔ Go ​

  • رابط‌ها سمت مصرف‌کننده‌اند. OrderRepository را در sales (مصرف‌کننده) تعریف کنید، نه در بستهٔ Postgres؛ بستهٔ Postgres sales را import می‌کند، نه برعکس.
  • رابط بپذیر، struct برگردان برای سازنده‌ها صادق است (postgres.New مقدار *Repository می‌دهد) در حالی که لایهٔ برنامه رابط را نگه می‌دارد.
  • context.Context همیشه اول؛ در نسخهٔ ما تراکنش هم روی آن سوار است.
  • خطاهای sentinel (ErrNotFound، ErrConcurrentModification) با errors.Is مقایسه می‌شوند؛ use case به 404 و 409 نگاشتشان می‌کند.
  • ژنریک برای repository نه. Repository[T any] کامپایل می‌شود ولی دقیقاً تفاوت‌های هر aggregate را پاک می‌کند.
  • sqlc به‌جای ORM وقتی schema مال شماست؛ GORM یا ent وقتی SQL کمتر می‌خواهید، ولی نگاشت به شیء دامنه باز کد شماست.
  • کپی struct ارزان است. از Get یک *Order تازه برگردانید؛ اشاره‌گری به داخل کش ندهید.

Laravel ​

snippetها PHP 8.4 برای Laravel 13 هستند و مرور و با php -l بررسی نحوی شده‌اند؛ repository درون‌حافظه بدون فریم‌ورک smoke-run شد؛ repositoryهای دیتابیسی اینجا اجرا نشده‌اند.

دامنه: aggregate، رابط، specificationها ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Domain;

/**
 * Persistence-oriented repository of the Order aggregate: one per aggregate
 * root, whole aggregates in and out, no Builder, no table names.
 * Implementations never commit a transaction the caller opened.
 */
interface OrderRepository
{
    /** @throws OrderNotFound */
    public function get(string $id): Order;

    /**
     * Insert (version 0) or update-if-version-matches.
     *
     * @throws ConcurrentModification when the stored version moved
     */
    public function save(Order $order): void;

    /** @throws OrderNotFound */
    public function remove(string $id): void;

    /** @return list<Order> */
    public function findSatisfying(OrderSpecification $spec): array;
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Domain;

use DateTimeImmutable;

/** The domain-language query "placed, still unpaid after N seconds". */
final class UnpaidLongerThan
{
    public static function spec(DateTimeImmutable $now, int $ageSeconds): OrderSpecification
    {
        return new AllOf(
            new InStatus('placed'),
            new PlacedBefore($now->modify("-{$ageSeconds} seconds")),
        );
    }
}

گزینهٔ ۲: Eloquent به شیء دامنه نگاشت می‌شود ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Persistence model for the orders table: a row, not the aggregate.
 * Used only inside EloquentOrderRepository.
 */
final class OrderRecord extends Model
{
    protected $table = 'orders';
    public $incrementing = false;
    protected $keyType = 'string';
    public $timestamps = false;
    protected $guarded = [];

    protected function casts(): array
    {
        return ['placed_at' => 'datetime', 'version' => 'integer'];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLineRecord::class, 'order_id');
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use App\Sales\Domain\AllOf;
use App\Sales\Domain\AnyOf;
use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\ForCustomer;
use App\Sales\Domain\InStatus;
use App\Sales\Domain\Not;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\OrderSpecification;
use App\Sales\Domain\PlacedBefore;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

/**
 * Option 2: Eloquent is the mapper, the domain object is the aggregate.
 * Eloquent models never leave this class. Joins the caller's transaction
 * (DB::transaction in the application service); it never commits one.
 */
final class EloquentOrderRepository implements OrderRepository
{
    public function get(string $id): Order
    {
        $record = OrderRecord::query()->with('lines')->find($id);
        if ($record === null) {
            throw new OrderNotFound($id);
        }

        return $this->toDomain($record);
    }

    public function save(Order $order): void
    {
        $s = $order->snapshot();
        $attrs = [
            'customer_id' => $s['customer_id'],
            'currency' => $s['currency'],
            'status' => $s['status'],
            'placed_at' => $s['placed_at'],
        ];

        // Inside the application service's DB::transaction this becomes a nested
        // transaction (Laravel issues a SAVEPOINT); standalone it is our own.
        DB::transaction(function () use ($s, $attrs, $order): void {
            if ($s['version'] === 0) {
                OrderRecord::query()->insert(['id' => $s['id'], 'version' => 1] + $attrs);
            } else {
                $updated = OrderRecord::query()
                    ->whereKey($s['id'])
                    ->where('version', $s['version'])
                    ->update($attrs + ['version' => $s['version'] + 1]);
                if ($updated === 0) {
                    throw new ConcurrentModification($s['id']);
                }
            }

            OrderLineRecord::query()->where('order_id', $s['id'])->delete();
            OrderLineRecord::query()->insert(array_map(
                fn (array $l) => ['order_id' => $s['id']] + $l,
                $s['lines'],
            ));

            foreach ($order->pendingEvents() as $event) {
                DB::table('outbox')->insert([
                    'topic' => OutboxTopics::for($event),
                    'payload' => json_encode($event, JSON_THROW_ON_ERROR),
                    'created_at' => now(),
                ]);
            }
        });

        $order->persisted($s['version'] + 1); // only after the transaction succeeded
    }

    public function remove(string $id): void
    {
        if (OrderRecord::query()->whereKey($id)->delete() === 0) { // lines: ON DELETE CASCADE
            throw new OrderNotFound($id);
        }
    }

    public function findSatisfying(OrderSpecification $spec): array
    {
        $query = OrderRecord::query()->with('lines'); // one extra query, not N+1
        $query->where(fn (Builder $q) => $this->apply($q, $spec));

        return $query->orderBy('id')->get()->map(fn (OrderRecord $r) => $this->toDomain($r))->all();
    }

    /** Translate known specs to SQL; refuse anything else loudly. */
    private function apply(Builder $q, OrderSpecification $spec): void
    {
        match (true) {
            $spec instanceof ForCustomer => $q->where('customer_id', $spec->customerId),
            $spec instanceof InStatus => $q->where('status', $spec->status),
            $spec instanceof PlacedBefore => $q->where('placed_at', '<', $spec->at->format('Y-m-d H:i:s')),
            $spec instanceof Not => $q->whereNot(fn (Builder $n) => $this->apply($n, $spec->spec)),
            $spec instanceof AllOf => $q->where(function (Builder $n) use ($spec): void {
                foreach ($spec->specs as $s) {
                    $n->where(fn (Builder $c) => $this->apply($c, $s));
                }
            }),
            $spec instanceof AnyOf => $q->where(function (Builder $n) use ($spec): void {
                foreach ($spec->specs as $s) {
                    $n->orWhere(fn (Builder $c) => $this->apply($c, $s));
                }
            }),
            default => throw new InvalidArgumentException('cannot translate ' . $spec::class . ' to SQL'),
        };
    }

    private function toDomain(OrderRecord $r): Order
    {
        return Order::reconstitute([
            'id' => $r->id,
            'customer_id' => $r->customer_id,
            'currency' => $r->currency,
            'status' => $r->status,
            'placed_at' => $r->placed_at?->format('Y-m-d H:i:s'),
            'version' => (int) $r->version,
            'lines' => $r->lines->sortBy('sku')->map(fn (OrderLineRecord $l) => [
                'sku' => $l->sku,
                'quantity' => (int) $l->quantity,
                'unit_price_minor' => (int) $l->unit_price_minor,
            ])->values()->all(),
        ]);
    }
}

گزینهٔ ۳: فقط query builder ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\ForCustomer;
use App\Sales\Domain\InStatus;
use App\Sales\Domain\AllOf;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\OrderSpecification;
use App\Sales\Domain\PlacedBefore;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

/**
 * Option 3: no Eloquent models at all. Plain query builder rows are mapped by
 * hand. Most control and fewest surprises (no hydration, no events, no
 * lazy loading), most code. Same contract as the Eloquent variant.
 */
final class QueryBuilderOrderRepository implements OrderRepository
{
    public function get(string $id): Order
    {
        $row = DB::table('orders')->where('id', $id)->first();
        if ($row === null) {
            throw new OrderNotFound($id);
        }

        return $this->hydrate($row, $this->linesFor([$id])[$id] ?? []);
    }

    public function save(Order $order): void
    {
        $s = $order->snapshot();
        $attrs = [
            'customer_id' => $s['customer_id'],
            'currency' => $s['currency'],
            'status' => $s['status'],
            'placed_at' => $s['placed_at'],
        ];

        DB::transaction(function () use ($s, $attrs, $order): void {
            if ($s['version'] === 0) {
                DB::table('orders')->insert(['id' => $s['id'], 'version' => 1] + $attrs);
            } else {
                $updated = DB::table('orders')
                    ->where('id', $s['id'])
                    ->where('version', $s['version']) // compare-and-set
                    ->update($attrs + ['version' => $s['version'] + 1]);
                if ($updated === 0) {
                    throw new ConcurrentModification($s['id']);
                }
            }
            DB::table('order_lines')->where('order_id', $s['id'])->delete();
            if ($s['lines'] !== []) {
                DB::table('order_lines')->insert(array_map(
                    fn (array $l) => ['order_id' => $s['id']] + $l,
                    $s['lines'],
                ));
            }
            foreach ($order->pendingEvents() as $event) {
                DB::table('outbox')->insert([
                    'topic' => OutboxTopics::for($event),
                    'payload' => json_encode($event, JSON_THROW_ON_ERROR),
                    'created_at' => now(),
                ]);
            }
        });

        $order->persisted($s['version'] + 1);
    }

    public function remove(string $id): void
    {
        if (DB::table('orders')->where('id', $id)->delete() === 0) {
            throw new OrderNotFound($id);
        }
    }

    public function findSatisfying(OrderSpecification $spec): array
    {
        $rows = DB::table('orders')
            ->where(fn (Builder $q) => $this->apply($q, $spec))
            ->orderBy('id')
            ->get();
        $lines = $this->linesFor($rows->pluck('id')->all());

        return $rows->map(fn (object $r) => $this->hydrate($r, $lines[$r->id] ?? []))->all();
    }

    private function apply(Builder $q, OrderSpecification $spec): void
    {
        match (true) {
            $spec instanceof ForCustomer => $q->where('customer_id', $spec->customerId),
            $spec instanceof InStatus => $q->where('status', $spec->status),
            $spec instanceof PlacedBefore => $q->where('placed_at', '<', $spec->at->format('Y-m-d H:i:s')),
            $spec instanceof AllOf => $q->where(function (Builder $n) use ($spec): void {
                foreach ($spec->specs as $s) {
                    $n->where(fn (Builder $c) => $this->apply($c, $s));
                }
            }),
            default => throw new InvalidArgumentException('cannot translate ' . $spec::class . ' to SQL'),
        };
    }

    /**
     * @param list<string> $ids
     * @return array<string, list<array{sku: string, quantity: int, unit_price_minor: int}>>
     */
    private function linesFor(array $ids): array
    {
        $out = [];
        foreach (DB::table('order_lines')->whereIn('order_id', $ids)->orderBy('sku')->get() as $l) {
            $out[$l->order_id][] = [
                'sku' => $l->sku,
                'quantity' => (int) $l->quantity,
                'unit_price_minor' => (int) $l->unit_price_minor,
            ];
        }

        return $out;
    }

    /** @param list<array{sku: string, quantity: int, unit_price_minor: int}> $lines */
    private function hydrate(object $r, array $lines): Order
    {
        return Order::reconstitute([
            'id' => $r->id,
            'customer_id' => $r->customer_id,
            'currency' => $r->currency,
            'status' => $r->status,
            'placed_at' => $r->placed_at,
            'version' => (int) $r->version,
            'lines' => $lines,
        ]);
    }
}

گزینهٔ ۱: Eloquent خودِ aggregate است ​

php
<?php

declare(strict_types=1);

namespace App\Sales\EloquentAggregate;

use DomainException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Option 1: the Eloquent model IS the aggregate. Repository is thin or absent:
 * Order::query()->with('lines')->findOrFail($id) is the "repository". The
 * price: the persistence API (save, update, delete, relations, mass
 * assignment) is public on the aggregate, so discipline replaces enforcement.
 */
final class Order extends Model
{
    protected $table = 'orders';
    public $incrementing = false;
    protected $keyType = 'string';
    public $timestamps = false;
    // Nothing is mass assignable: state changes only through the methods below.
    protected $fillable = [];

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class, 'order_id');
    }

    public static function draft(string $id, string $customerId, string $currency): self
    {
        $o = new self();
        $o->forceFill(['id' => $id, 'customer_id' => $customerId, 'currency' => $currency,
            'status' => 'draft', 'version' => 0]);

        return $o;
    }

    public function place(): void
    {
        if ($this->status !== 'draft') {
            throw new DomainException('only a draft order can be placed');
        }
        $this->status = 'placed';
    }

    /**
     * Optimistic save: the UPDATE carries the version we loaded.
     * Eloquent has no built-in version column, so we add the check ourselves.
     */
    public function saveWithVersion(): void
    {
        $loaded = (int) $this->getOriginal('version');
        if (!$this->exists) {
            $this->version = 1;
            $this->save();

            return;
        }
        $updated = self::query()
            ->whereKey($this->getKey())
            ->where('version', $loaded)
            ->update($this->getDirty() + ['version' => $loaded + 1]);
        if ($updated === 0) {
            throw new \App\Sales\Domain\ConcurrentModification((string) $this->getKey());
        }
        $this->version = $loaded + 1;
        $this->syncOriginal();
    }
}

Fake، سرویس برنامه و binding ​

php
<?php

declare(strict_types=1);

namespace App\Sales\Infrastructure;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\Order;
use App\Sales\Domain\OrderNotFound;
use App\Sales\Domain\OrderRepository;
use App\Sales\Domain\OrderSpecification;

/**
 * Fake for unit tests. Stores snapshots, not live objects, so a loaded order
 * changes nothing until save() (same as a database). Passes the same contract
 * as the real repositories: see tests/OrderRepositoryContract.php.
 */
final class InMemoryOrderRepository implements OrderRepository
{
    /** @var array<string, array<string, mixed>> */
    private array $rows = [];

    /** @var list<object> what the outbox table would hold */
    public array $storedEvents = [];

    public function get(string $id): Order
    {
        if (!isset($this->rows[$id])) {
            throw new OrderNotFound($id);
        }

        return Order::reconstitute($this->rows[$id]);
    }

    public function save(Order $order): void
    {
        $s = $order->snapshot();
        $stored = $this->rows[$s['id']] ?? null;
        if (($stored === null && $s['version'] !== 0) || ($stored !== null && $stored['version'] !== $s['version'])) {
            throw new ConcurrentModification($s['id']);
        }
        $s['version']++;
        $this->rows[$s['id']] = $s;
        array_push($this->storedEvents, ...$order->pendingEvents());
        $order->persisted($s['version']);
    }

    public function remove(string $id): void
    {
        if (!isset($this->rows[$id])) {
            throw new OrderNotFound($id);
        }
        unset($this->rows[$id]);
    }

    public function findSatisfying(OrderSpecification $spec): array
    {
        $ids = array_keys($this->rows);
        sort($ids);
        $orders = array_map(fn (string $id) => Order::reconstitute($this->rows[$id]), $ids);

        return array_values(array_filter($orders, fn (Order $o) => $spec->isSatisfiedBy($o)));
    }
}
php
<?php

declare(strict_types=1);

namespace App\Sales\Application;

use App\Sales\Domain\ConcurrentModification;
use App\Sales\Domain\OrderRepository;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;

/**
 * Application service: owns the transaction. The repository never commits.
 * DB::transaction(..., attempts: 3) retries only on deadlocks, so the
 * optimistic-lock retry is an explicit loop around it.
 */
final class PlaceOrderHandler
{
    public function __construct(private readonly OrderRepository $orders)
    {
    }

    public function handle(string $orderId): void
    {
        for ($attempt = 1; ; $attempt++) {
            try {
                DB::transaction(function () use ($orderId): void {
                    $order = $this->orders->get($orderId);
                    $order->place(new DateTimeImmutable());
                    $this->orders->save($order); // aggregate + outbox row, one commit
                });

                return;
            } catch (ConcurrentModification $e) {
                if ($attempt >= 3) {
                    throw $e;
                }
            }
        }
    }
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Sales\Domain\OrderRepository;
use App\Sales\Infrastructure\EloquentOrderRepository;
use Illuminate\Support\ServiceProvider;

final class SalesServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Swap the binding to QueryBuilderOrderRepository or, in tests, to
        // InMemoryOrderRepository; callers only know the interface.
        $this->app->bind(OrderRepository::class, EloquentOrderRepository::class);
    }
}
php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $t): void {
            $t->string('id')->primary();
            $t->string('customer_id')->index();
            $t->char('currency', 3);
            $t->string('status');
            $t->timestamp('placed_at')->nullable();
            $t->unsignedInteger('version')->default(1);
            $t->index(['status', 'placed_at']);
        });
        Schema::create('order_lines', function (Blueprint $t): void {
            $t->string('order_id');
            $t->string('sku');
            $t->unsignedInteger('quantity');
            $t->bigInteger('unit_price_minor');
            $t->primary(['order_id', 'sku']);
            $t->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete();
        });
        // Written in the same transaction as the aggregate (outbox chapter).
        Schema::create('outbox', function (Blueprint $t): void {
            $t->id();
            $t->string('topic');
            $t->json('payload');
            $t->timestamp('created_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('outbox');
        Schema::dropIfExists('order_lines');
        Schema::dropIfExists('orders');
    }
};
php
<?php

declare(strict_types=1);

namespace Tests\Sales;

use App\Sales\Domain\OrderRepository;
use App\Sales\Infrastructure\EloquentOrderRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * The same contract against a real database. RefreshDatabase runs each test
 * inside a transaction (Laravel 13 docs), which is another reason repositories
 * must never commit on their own.
 */
final class EloquentOrderRepositoryTest extends TestCase
{
    use OrderRepositoryContract;
    use RefreshDatabase;

    protected function repository(): OrderRepository
    {
        return new EloquentOrderRepository();
    }
}

زاویهٔ Laravel ​

  • Eloquent یک Active Record است، پس گزینهٔ aggregate-به‌جای-مدل دامنه و ذخیره‌سازی را جفت می‌کند؛ بحث در Data Persistence Design.
  • $fillable = [] (یا $guarded = ['*']) روی مدل‌های شبیه aggregate تغییر state را مجبور به عبور از متدها می‌کند.
  • with('lines') با یک query اضافه eager load می‌کند و پاسخ Eloquent به N+1 است؛ Model::preventLazyLoading() می‌تواند lazy load را در توسعه به خطا تبدیل کند (پیش از استفاده فراخوانی دقیق را در مستندات Eloquent نسخهٔ ۱۳ ببینید).
  • DB::transaction(fn, attempts: n) فقط deadlock را retry می‌کند؛ retry تعارض version حلقهٔ شماست.
  • DB::transaction تودرتو savepoint می‌سازد، پس repository می‌تواند نوشتن‌هایش را در DB::transaction بپیچد و باز به handler بپیوندد.
  • lockForUpdate() جایگزین بدبینانه برای ستون version در ردیف‌های داغ است؛ Locks & Concurrency.
  • binding در service container ($this->app->bind(OrderRepository::class, ...)) راه عوض کردن پیاده‌سازی در تست و محیط‌هاست.
  • Doctrine ORM کتابخانهٔ PHP با unit of work و identity map واقعی است؛ اگر معنای collection-oriented را در PHP می‌خواهید آنجاست، به قیمت ترک Eloquent در آن context.

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

مسئلهراه‌حلچگونهمزیتهزینه
SQL در use caseهارابط repository برای هر ریشهOrderRepository در بستهٔ دامنهuse caseها مثل کسب‌وکار خوانده می‌شوندیک کلاس برای هر aggregate
Lost updateستون versionUPDATE ... WHERE version = $loadedقفلی نگه نمی‌داردretry هنگام تعارض
aggregate نیمه‌ذخیرهیک تراکنش برای هر use caseUnitOfWork.Do، DB::transactionaggregate و outbox اتمیکwiring تراکنش
تست دامنهٔ کندfake درون‌حافظه + contract testmemory.New()میلی‌ثانیه، همچنان صادقنگهداری fake
N+1 هنگام loadدو query، = ANY / whereInlineهای همهٔ idها یک‌جاتعداد query ثابتنگاشت با id
منطق پرس‌وجوی تکراریSpecificationUnpaidLongerThanقاعدهٔ نام‌دار، تست درون‌حافظهیک شاخهٔ مترجم برای هر spec
لیست‌ها دنیا را load می‌کنندQuery service / read modelquery DTO تختسریع، صفحه‌بندی‌شدهمسیر خواندن دوم
دامنه به Eloquent وابسته استگزینهٔ ۲ یا ۳OrderRecord + mapperدامنهٔ خالصکد نگاشت
کش کهنهdecorator با باطل‌سازیکش snapshot، با Save باطلخواندن سریع‌ترپیچیدگی
رویداد شبح یا گم‌شدهردیف outbox در Saveهمان تراکنشانتشار at-least-onceprocess relay

گذار از دروازهٔ جدول به repository، قدم‌به‌قدم ​

text
     Refactor: OrderDao (CRUD برای هر جدول) -> OrderRepository (یکی برای هر aggregate)
1    use caseهایی را فهرست کنید که orders و order_lines را لمس می‌کنند؛ مرز aggregate را روی دیوار بکشید
2    رابط repository را فقط از نیاز use caseها بنویسید (Get، Save، یک finder)
3    اعتبارسنجی را از سرویس‌ها به متدهای Order ببرید؛ فیلدهای Order را خصوصی کنید
4    Snapshot و Reconstitute را اضافه کنید؛ contract test را روی کد قدیمی با یک adapter بنویسید
5    repository Postgres/Eloquent را پیاده کنید؛ contract test را تا سبز شدن اجرا کنید
6    use caseها را یکی‌یکی به رابط ببرید؛ متدهای DAO را که دیگر استفاده نمی‌شوند حذف کنید
7    query لیست و گزارش را به query service ببرید؛ Paginate/Where را از repository حذف کنید
8    ستون version را اضافه کنید (expand/contract)، سپس بررسی را فعال کنید
قبلبعد
OrderDao.UpdateStatus(id, "paid")order.MarkPaid() سپس orders.Save(order)
LineDao.SetQty(id, sku, 5)order.AddLine(sku, 5, price)
OrderDao.Search(filters)OrderQueries.ListFor(customer, cursor)
repo.Query().Where(...) در controllerfinder نام‌دار یا specification
سرویس بعد از هر DAO tx.Commit() می‌زندیک UnitOfWork.Do برای هر use case

انتخاب ​

وضعیتتوصیهتکنیک اضافهدلیل
دامنهٔ هسته، invariantهای غنیrepository ذخیره‌محور، نگاشت‌شده (Laravel گزینهٔ ۲، snapshot در Go)contract test، ستون versionقواعد روی هر تغییر اجرا می‌شوند
context عمومی یا CRUD (ادمین Catalog، تنظیمات)Eloquent به‌عنوان aggregate یا بدون repository$fillable = []repository محافظتی اضافه نمی‌کند
سرویس Goرابط در دامنه، پیاده‌سازی pgx یا sqlcfake + contract testبدون change tracking، SQL صریح
تیم روی Hibernate، Doctrine یا EFcollection-oriented روی unit of work خود ORMباز هم یک repository برای هر ریشهORM از قبل دنبال می‌کند
مسیر خواندن داغquery service با DTO تختکش، صفحه‌بندی keysetaggregate برای دستور است
ردیف داغ نوشتن (شمارندهٔ موجودی)lockForUpdate یا UPDATE اتمیک داخل repositoryستون version به‌عنوان پشتیبانretryهای خوش‌بینانه روی یک ردیف می‌چرخند
aggregate با event sourcingrepository رویدادها را می‌خواند و بازسازی می‌کندsnapshotstate همان جریان رویداد است
گزارش بین contextهاread model یا warehouseCDCهرگز repository بین contextها
aggregate بزرگ (صدها فرزند)مرز را بازنگری کنیدaggregateهای کوچک‌تر، ارجاع با idload کامل مقیاس نمی‌گیرد
schema قدیمی جدول‌هاگزینهٔ ۳ یا persistence modelview، mapperدامنه تمیز می‌ماند

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

مونولیت: یک process، یک دیتابیس ​

مثال روزمره checkout فروشگاه آنلاین است. PlaceOrderHandler یک DB::transaction باز می‌کند، repository Order را می‌خواند، دامنه آن را ثبت می‌کند، repository سفارش، lineها و یک ردیف outbox را در همان تراکنش ذخیره می‌کند. repositoryها اشیای درون‌process هستند؛ Get و Save queryهای چند میلی‌ثانیه‌ای روی یک PostgreSQL‌اند. تعارض همزمانی نادر است و با حلقهٔ سه‌تلاشه مدیریت می‌شود. هرچه در فصل‌های دیتابیس آمده (isolation، قفل، connection pool) مستقیم صدق می‌کند: Connection Pooling.

مونولیت ماژولار و چند دیتابیس ​

هر bounded context (Sales، Fulfilment، Billing، Catalog، Identity) repositoryها و جدول‌های خودش را دارد، معمولاً در schema جدا (sales.orders، fulfilment.shipments) و با نقش دیتابیس برای هر ماژول. قاعده‌ها:

قاعدهمثالچرا
یک repository برای هر ریشه، داخل contextشsales.OrderRepository، fulfilment.ShipmentRepositoryمالکیت در importها دیده می‌شود
هیچ repositoryای از context رد نمی‌شودFulfilment هرگز sales.OrderRepository را صدا نمی‌زندداده بین contextها با API منتشرشده یا رویداد
بدون join بین schemaها در repositoryFulfilment order_id را به‌عنوان id نگه می‌دارد، نه کلید خارجی به salescontextها بعداً قابل جدا شدن می‌مانند
خواندن بین contextها با رابط پرس‌وجوcatalog.PriceLookupقرارداد، نه جدول
تست معماریPest arch()، تست import با go listقاعده‌ها در CI اجرا می‌شوند

نگاه کنید Modular Monolith و Data Ownership. fake برای هر context تست ماژول‌ها را مستقل می‌کند.

میکروسرویس: یک repository برای هر aggregate داخل سرویس ​

وقتی Sales و Fulfilment سرویس می‌شوند، repositoryها جابه‌جا نمی‌شوند؛ داخل سرویس خودشان می‌مانند و طرف دیگر با API یا رویداد صدا زده می‌شود (Service Communication، Service Boundaries).

text
     مثال تولیدی: سفارش ثبت شد -> محموله ساخته شد (دو سرویس، دو دیتابیس)
1    Sales: POST /orders/42/placement
2    Sales: BEGIN; orders.Get(42); order.Place(); orders.Save(order)  -- orders + lines + ردیف outbox
3    Sales: COMMIT
4    Sales relay: ردیف outbox -> broker  topic sales.order.placed.v1
5    Fulfilment consumer: حذف تکراری با inbox روی شناسهٔ رویداد
6    Fulfilment: BEGIN; shipment := NewShipment(orderID); shipments.Save(shipment); COMMIT
7    Fulfilment هرگز sales.orders را لمس نمی‌کند؛ order_id و lineهای لازم را از رویداد نگه می‌دارد
نیاز بین سرویس‌هاغلطدرست
Fulfilment به lineهای سفارش نیاز داردجدول Sales را با repository مشترک بخواندرویداد lineها را می‌آورد، یا Sales GET /orders/{id} می‌دهد
Billing جمع را می‌خواهدsales.OrderRepository را import کندرویداد جمع را می‌آورد؛ Billing فاکتور خودش را نگه می‌دارد
Sales موجودی می‌خواهدinventory.stock را join کندAPI موجودی یا کپی خواندنی محلی
تغییر اتمیک چندسرویسیتراکنش توزیع‌شده در SaveSaga (Saga Pattern)

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

وضعیتاثر روی repositoryهاراه‌کار
Read replicaGet از replica ممکن است کهنه باشد، سپس Save روی version تعارض می‌کندمسیر دستور از primary می‌خواند؛ queryهای لیست از replica (Replication & Failover)
کش جلوی Getaggregate کهنهکش snapshot + باطل‌سازی + بررسی version
دیتابیس shard‌شدهaggregate نباید روی چند shard بیفتدکلید shard = id aggregate یا tenant (Partitioning & Sharding)
چندمنطقهٔ active-activeیک aggregate در دو منطقه نوشته می‌شودنوشتن‌های یک aggregate را به یک منطقه بفرستید، یا CRDT/merge در مدل
تکرار relay در outboxمصرف‌کننده رویداد را دو بار می‌بیندمصرف‌کنندهٔ idempotent با inbox
Failoverآخرین نوشتن commit‌شده روی primary جدید ممکن است قدیمی‌تر باشدErrConcurrentModification را مدیریت و دستورها را دوباره اجرا کنید؛ دستورها باید idempotent باشند

مسیر مقیاس: ۱×، ۱۰×، ۱۰۰× ​

بارشکل repositoryچه عوض می‌شود
۱×repository نگاشت‌شده، Save با جایگزینی فرزندان، بدون کشچیز خاصی نیست
۱۰×diff فرزندان به‌جای جایگزینی، finderهای index‌دار، read model برای لیست، replica برای queryquery service ظاهر می‌شود
۱۰۰×decorator کش snapshot روی aggregateهای داغ، جدول‌های partition‌شده، shard به‌ازای tenant، outbox با CDCمرز aggregateها بازنگری می‌شود؛ ردیف‌های داغ UPDATE اتمیک یا قفل بدبینانه می‌گیرند
فراترaggregateهای event-sourced برای پرکارترین‌ها، snapshot هر N رویدادپیاده‌سازی متفاوت پشت همان رابط

آزمایشگاه: یک contract، سه پیاده‌سازی ​

Expected, not run: قدم‌های Postgres دیتابیس می‌خواهند؛ قدم‌های درون‌حافظه اجرا شدند.

text
     Setup
1    cd docs/snippets/ddd/repositories/go
2    go vet ./... && go test ./...
     ok  academy/repositories/memory    ... contract روی repository درون‌حافظه پاس می‌شود
     ok  academy/repositories/style     ... ماشین collection-oriented
3    createdb repos_lab && psql repos_lab -f postgres/schema.sql
4    DATABASE_URL=postgres://localhost/repos_lab go test ./postgres -run Contract -v
     expected: همان هفت زیرتست روی Postgres هم پاس می‌شوند
text
     آزمایش‌ها
1    fake را عمداً خراب کنید: بررسی version را از memory.Save بردارید.
     expected: "stale save fails with ErrConcurrentModification" شکست می‌خورد؛ contract انحراف را گرفت
2    دو session ـِ psql: هر دو BEGIN، هر دو SELECT version FROM orders WHERE id='o-3' (4)؛ A با WHERE version=4 به‌روز و commit می‌کند؛ B همان را اجرا می‌کند
     expected: B می‌گوید UPDATE 0
3    درج outbox را از Save بردارید. تست app را اجرا کنید.
     expected: TestPlaceOrderSavesAndRecordsEvent شکست می‌خورد: stored events = 0
4    یک spec جدید (PlacedAfter) بدون شاخهٔ مترجم بسازید و FindSatisfying را روی Postgres صدا بزنید
     expected: ErrUnsupportedSpec، نه اسکن کامل جدول
5    با cache.Wrap بپیچید و contract را اجرا کنید
     expected: پاس؛ سپس باطل‌سازی را در Save کامنت کنید: TestSaveInvalidatesCache شکست می‌خورد
sql
-- Experiment 2 (two psql sessions)
-- A: BEGIN; SELECT version FROM orders WHERE id = 'o-3';          -- 4
-- B: BEGIN; SELECT version FROM orders WHERE id = 'o-3';          -- 4
-- A: UPDATE orders SET status='paid', version=version+1 WHERE id='o-3' AND version=4;  -- UPDATE 1
-- A: COMMIT;
-- B: UPDATE orders SET status='cancelled', version=version+1 WHERE id='o-3' AND version=4;  -- UPDATE 0
-- B: ROLLBACK;  -- application reloads and retries

برای Laravel: php artisan migrate و سپس php artisan test --filter=OrderRepositoryTest؛ کلاس‌های تست in-memory، Eloquent و query-builder یک trait مشترک دارند (expected, not run).

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

باورواقعیت
«Repository همان DAO با اسم قشنگ‌تر است»DAO برای هر جدول CRUD است؛ repository برای هر ریشهٔ aggregate با finderهای دامنه
«هر entity repository می‌خواهد»فقط ریشه‌ها؛ lineها از طریق ریشه در دسترس‌اند
«در DDD repository متد Save ندارد»آن سبک collection-oriented است که change tracking می‌خواهد؛ Go و Eloquent از Save استفاده می‌کنند
«Save باید commit کند»سرویس برنامه مالک تراکنش است؛ repository می‌پیوندد
«Repository برای عوض کردن دیتابیس است»برای دور نگه داشتن ماندگاری از مدل است؛ عوض کردن اثر جانبی است
«Repository<T> عمومی کد کم می‌کند»معنای aggregate را پاک می‌کند و نشت Where/Raw را دعوت می‌کند
«مدل Eloquent را از repository برگردان، مشکلی نیست»آن‌گاه save() و relationها عمومی‌اند؛ گزینهٔ ۱ است با هزینه‌های گزینهٔ ۱
«mock به‌اندازهٔ fake خوب است»fake با contract test انحراف رفتاری را می‌گیرد؛ mock فقط فراخوانی‌ها را می‌سنجد
«تراکنش جلوی lost update را می‌گیرد»زیر READ COMMITTED نه؛ ستون version یا قفل لازم است
«Pagination کار repository است»لیست‌ها دغدغهٔ پرس‌وجو هستند؛ query service
«شیء aggregate را کش کن»snapshot را کش کنید و نمونهٔ تازه بدهید
«رویداد را از Save منتشر کن»در همان تراکنش در outbox ذخیره کنید؛ بعداً منتشر کنید

چکیده (Cheat sheet) ​

موضوعچه چیزی را یادتان بماند
دامنهیک repository برای هر ریشهٔ aggregate، aggregate کامل رفت و برگشت
خانهٔ رابطبستهٔ دامنه؛ پیاده‌سازی‌ها در infrastructure
حداقل متدهاGet، Save، Remove (در صورت نیاز)، یک یا دو finder دامنه
سبکPersistence-oriented در Go و Eloquent؛ collection-oriented فقط با unit of work واقعی
در آن نمی‌آیدلیست، pagination، گزارش، Where، Raw، Builder
تراکنشسرویس برنامه شروع و commit می‌کند؛ repository می‌پیوندد
همزمانیستون version؛ UPDATE ... WHERE version = $loaded؛ ۰ ردیف یعنی تعارض
Reconstitutionجدا از factory؛ بدون دستور، بدون رویداد
Specificationنام‌دار و ترکیب‌پذیر؛ شناخته‌شده‌ها را ترجمه، ناشناخته را رد کنید
Laravelگزینهٔ ۱ برای CRUD، گزینهٔ ۲ برای هسته، گزینهٔ ۳ برای مسیر داغ
تستfake به‌علاوهٔ یک contract test مشترک
رویدادaggregate ثبت می‌کند؛ Save در outbox ذخیره می‌کند؛ relay منتشر می‌کند
کشdecorator snapshot، با نوشتن باطل شود، بررسی version بماند
قاعدهٔ contextهیچ repositoryای از bounded context رد نمی‌شود

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

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

۱ — چرا OrderLineRepository وجود ندارد؟ حیاتی ​

پاسخ

پاسخ: lineها داخل aggregate ‌Order هستند. ذخیره یا خواندن جداگانه‌شان invariantهای ریشه (سقف line، جمع، بررسی وضعیت) را دور می‌زند. فقط ریشه در دارد.

۲ — تفاوت repository مجموعه‌محور و ذخیره‌محور چیست و کدام به Go می‌خورد؟ مهم ​

پاسخ

پاسخ: مجموعه‌محور Add/Remove دارد و به unit of work برای فهمیدن تغییرها تکیه می‌کند؛ ذخیره‌محور Save دارد و فراخوان باید صدایش بزند. Go persistence context ندارد پس ذخیره‌محور (یا unit of work دست‌ساز) مناسب است.

۳ — چرا Save نباید commit کند؟ حیاتی ​

پاسخ

پاسخ: use case ممکن است چند ردیف یا چند aggregate به‌علاوهٔ ردیف outbox ذخیره کند؛ commit داخل Save اتمیک بودن را می‌شکند. سرویس برنامه مالک unit of work است.

۴ — Save چطور تغییر همزمان را تشخیص می‌دهد؟ مهم ​

پاسخ

پاسخ: aggregate یک version دارد. UPDATE ... WHERE id = $1 AND version = $loaded اگر تراکنش دیگری زودتر ذخیره کرده باشد صفر ردیف را عوض می‌کند و repository ErrConcurrentModification برمی‌گرداند.

۵ — آیا DB::transaction($cb, attempts: 3) تعارض version را retry می‌کند؟ مهم ​

پاسخ

پاسخ: خیر. مستندات Laravel attempts را تعداد retry هنگام deadlock توصیف می‌کند. ConcurrentModification از repository شما حلقهٔ retry صریح دور تراکنش می‌خواهد.

۶ — چرا Reconstitute جدا از سازنده؟ مهم ​

پاسخ

پاسخ: قواعد و رویدادهای ایجاد نباید هنگام load state ذخیره‌شده اجرا شوند. reconstitution به state ذخیره‌شده اعتماد می‌کند، فقط آنچه خرابی می‌شکند را اعتبارسنجی می‌کند و رویداد ثبت نمی‌کند.

۷ — چه زمانی Eloquent-به‌عنوان-aggregate قابل قبول است؟ تکمیلی ​

پاسخ

پاسخ: در contextهای عمومی یا پرCRUD با invariant کم، که repository نگاشت‌شده کد اضافه می‌کند ولی محافظتی نه. $fillable را خالی نگه دارید و متدهای دامنه اضافه کنید.

۸ — چرا fake به‌علاوهٔ contract test و نه mock؟ مهم ​

پاسخ

پاسخ: fake رفتار واقعی دارد (version، کپی، خطا)؛ contract test همان caseها را روی fake و repository واقعی اجرا می‌کند تا fake منحرف نشود. mock فقط فراخوانی‌های نوشته‌شده را می‌سنجد.

۹ — «صفحهٔ ۳ لیست سفارش‌ها» کجا می‌نشیند؟ حیاتی ​

پاسخ

پاسخ: در query service یا read model که DTO تخت با صفحه‌بندی keyset برمی‌گرداند، نه در repository.

۱۰ — چرا repository نباید repository context دیگر را صدا بزند؟ حیاتی ​

پاسخ

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

۱۱ — رویدادی که aggregate ثبت کرده چطور با امنیت به broker می‌رسد؟ حیاتی ​

پاسخ

پاسخ: Save یک ردیف outbox در همان تراکنش درج می‌کند؛ relay بعد از commit منتشر می‌کند؛ مصرف‌کننده‌ها با inbox تکراری‌ها را حذف می‌کنند.

واژه‌نامه ​

اصطلاحمعنا
Repositoryرابط مجموعه‌مانند برای load و ذخیرهٔ aggregateهای کامل یک نوع ریشه
Aggregate rootentityای که aggregate از طریق آن در دسترس است و عوض می‌شود
Collection-oriented repositoryrepository با Add/Remove بدون save؛ به change tracking تکیه دارد
Persistence-oriented repositoryrepository با Save صریح
Unit of workمجموعه تغییرهایی که با هم commit می‌شوند؛ در مالکیت سرویس برنامه
Identity mapکش هر session که یک نمونه برای هر هویت تضمین می‌کند
Change trackingتشخیص اشیای تغییرکرده با مقایسهٔ snapshot، در Hibernate، Doctrine، EF Core
Specificationقاعدهٔ دامنهٔ نام‌دار با IsSatisfiedBy که با And، Or، Not ترکیب می‌شود
Subsumptionمقایسهٔ specificationها برای دیدن اینکه یکی دیگری را نتیجه می‌دهد یا نه
Reconstitutionساختن دوبارهٔ aggregate از state ذخیره‌شده بدون اجرای دستور
Snapshot / mementoکپی تخت state aggregate که از مرز ماندگاری می‌گذرد
Optimistic concurrencyتشخیص نوشتن رقیب با بررسی version به‌جای قفل
Version columnعدد صحیحی که با هر save بالا می‌رود و در WHERE می‌آید
Lost updateنوشتنی که نوشتن همزمان را بی‌صدا بازنویسی می‌کند
Read modelشکل داده فقط برای پرس‌وجو، ساخته‌شده برای صفحه یا گزارش
Query serviceکلاسی که SQL اجرا می‌کند و DTO تخت برمی‌گرداند، بیرون repository
DAOشیء دسترسی به داده: CRUD برای هر جدول، نه به شکل aggregate
Active Recordمدلی که هم ردیف خودش است هم API ماندگاری (Eloquent)
Data Mapperنگاشتگری که داده را بین شیء دامنه و ردیف جابه‌جا می‌کند
Fakeپیاده‌سازی سبک و کارا برای تست
Contract testیک مجموعه تست که روی هر پیاده‌سازی یک رابط اجرا می‌شود
Outboxجدولی که در همان تراکنش state نوشته و به broker relay می‌شود
sqlcابزاری که از queryهای SQL کد Go ایمن از نظر نوع می‌سازد
pgxدرایور و جعبه‌ابزار PostgreSQL برای Go
DBTXرابطی که هم pool هم تراکنش برآورده می‌کنند
Savepointنشانگر تراکنش تودرتو؛ Laravel برای DB::transaction تودرتو استفاده می‌کند
ErrConcurrentModificationخطای sentinel برای save با version کهنه

منابع ​

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