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 test | Fake و contract test |
| کش در repository | کش |
| رویدادهایی که aggregate ثبت میکند | انتشار رویداد هنگام ذخیره |
Repository<T> عمومی، DAO، نشت | ضدالگوها |
| مثال در Go | Go |
| مثال در Laravel | Laravel |
| هر context و هر سرویس | در معماری |
| عملی | آزمایشگاه |
| باورهای غلط، خلاصه، آزمون، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
واژگان. هر ردیف بعداً در فهرست مفاهیم باز میشود.
| اصطلاح | به زبان ساده | مثال کوچک | بدون آن چه میشود |
|---|---|---|---|
| Repository | دری شبیه مجموعه به aggregateهای ذخیرهشدهٔ یک نوع ریشه | OrderRepository.Get(id) یک Order کامل میدهد | SQL و نام جدول در use caseها پخش میشود |
| «ریشهٔ اگریگیت (Aggregate Root)» | تنها entityای که بیرونیها حق دارند نگه دارند و بخواهند | Order نه OrderLine | خطوط پشت سر ریشه ذخیره میشوند |
| Collection-oriented | شبیه set: Add و Remove، بدون save | Hibernate session، Doctrine با persist و flush | به change tracking نیاز دارید که شاید ندارید |
| Persistence-oriented | بعد از هر تغییر Save صریح | orders.Save(ctx, order) | فراموش کردن save |
| Specification | قاعدهٔ دامنه با نام و قابل ترکیب برای انتخاب aggregate | UnpaidLongerThan(now, 48h) | منطق پرسوجو در سرویسها تکرار میشود |
| Unit of Work | مرز یک commit، در مالکیت سرویس برنامه | DB::transaction(...)، UnitOfWork.Do | repository نصفهٔ یک use case را commit میکند |
| «همزمانی خوشبینانه (Optimistic Concurrency)» | تشخیص نوشتن رقیب با شمارهٔ version | UPDATE ... WHERE version = $loaded | Lost update بیصدا |
| Reconstitution | ساختن aggregate از state ذخیرهشده بدون اجرای دستور | sales.Reconstitute(snapshot) | state نامعتبر وارد میشود یا هنگام load رویداد میسوزد |
| Read Model | شکل فقطخواندنی برای صفحه یا گزارش | OrderListRow از یک view | لیستها aggregate را مجبور میکنند همهچیز را بیاورد |
سه شکل از یک رابط (مقایسه در مجموعهمحور در برابر ذخیرهمحور):
| سبک | متدها | چه کسی تغییر را میفهمد | خانهٔ طبیعی | هزینه |
|---|---|---|---|---|
| Collection-oriented | Add، Remove، Get، finder | unit of work ORM هنگام flush | Hibernate، Doctrine ORM، EF Core | identity map و change tracking لازم است |
| Persistence-oriented | Get، Save، Remove، finder | فراخوان با صدا زدن Save | Go، Eloquent، key-value و document store | یک فراخوانی بیشتر که باید یادتان بماند |
| Closure-style update | Update(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 عمومی میمانند |
| ۲. نگاشتشده | کلاس خالص PHP | OrderRecord را به 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).
تصویر نشان میدهد رابط repository داخل لایهٔ دامنه است، پیادهسازی بیرون آن، و aggregate کامل از مرز میگذرد. خطوط (lines) دری برای خودشان ندارند.
سه بدفهمی، همین اول
- «Repository پوششی دور ORM یا جدول است.» Repository پوششی دور یک aggregate است. یک جدول ممکن است به سه aggregate خدمت کند و یک aggregate ممکن است چهار جدول را بگیرد.
- «Repository برای این است که دیتابیس را عوض کنیم.» این یک اثر جانبی خوب است. هدف، دور نگه داشتن ماندگاری از مدل و دادن یک ورودی واحد به invariantهاست. Three Dots Labs صریح میگوید: "If you can swap the database, it's a sign that you implemented the repository pattern correctly"؛ یعنی محکی برای درستی الگو، نه هدف آن.
- «هر 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 به کار میبریم.
سال منبع چه مشکلی را حل کرد
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) که:
- برای هر ریشهٔ aggregate تعریف میشود (نه برای entity، نه برای جدول)؛
- aggregate کامل و معتبر برمیگرداند (نه entity نیمهبارشده از درون)؛
- aggregate کامل را برای ذخیره میگیرد پس invariantها چون ریشه درگیر بود اجرا میشوند؛
- finderهایی به زبان دامنه دارد (
FindSatisfying(UnpaidLongerThan(...))) نه فیلتر عمومی روی فیلد؛ - فناوری ذخیره، schema و زبان پرسوجو را پنهان میکند؛
- مالک تراکنش نیست: به تراکنشی میپیوندد که سرویس برنامه باز کرده.
فراخوان (سرویس برنامه) 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 صدا بزند.
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 checking | Collection-oriented | persist، flush هنگام commit |
| Doctrine ORM (PHP) | UnitOfWork، persist، flush | Collection-oriented | Doctrine لازم است، نه Eloquent |
| EF Core (.NET) | Change tracker | Collection-oriented | Microsoft: DbContext هم repository است هم unit of work |
| Eloquent (Laravel) | isDirty() برای هر مدل، بدون identity map | Persistence-oriented | relationها مدل جدا هستند |
Go database/sql، pgx، sqlc | هیچ | Persistence-oriented | SQL را خودتان مینویسید |
| GORM، ent (Go) | بهازای هر فراخوانی، بدون session ماندگار | Persistence-oriented | تراکنش با db.Transaction، client.Tx |
| MongoDB، Redis، DynamoDB | هیچ | Persistence-oriented | جایگزینی کل سند طبیعی است |
راهحل / نحوهٔ استفاده: در Go و Laravel ذخیرهمحور را بردارید. اگر تیم روی معنای مجموعه اصرار دارد، unit of work کوچک بخش Go را بسازید یا به Doctrine بروید؛ وانمود نکنید Eloquent aggregate را دنبال میکند.
// 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
}چه چیزی در 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 را نشت میدهد |
قاعدهٔ سرانگشتی برای 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 service | SELECT ... LIMIT با keyset به یک DTO |
| جستوجوی ادمین با فیلتر | Query service | Query builder یا موتور جستوجو |
| درآمد روزانه | انبار گزارش | materialised view، data warehouse |
| «این SKU هنوز قابل فروش است؟» | Catalog API یا read model | دادهٔ context دیگر، هرگز repository بین contextها |
| سفارشهایی که بعد از ۴۸ ساعت باید لغو شوند | Repository + specification | هر نتیجه بعداً هدف دستور است |
صفحهٔ لیست سفارشها
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 ترجمه میکند یا مجموعهٔ بزرگتری را میآورد و در حافظه فیلتر میکند.
سه کاربرد 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 در تست واحد بدون دیتابیس استفاده میشود.
راهحل / نحوهٔ استفاده:
-- 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);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)})
}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 ردیف دوم در همان تراکنش است.
| تکنیک | Go | Laravel |
|---|---|---|
| مالک تراکنش | سرویس برنامه با UnitOfWork.Do(ctx, fn) | DB::transaction(fn) در handler |
| repository چطور میپیوندد | pgx.Tx در context.Context | اتصال پیشفرض که در تراکنش است |
| جایگزین صریح | repository محدود به tx: repo.WithTx(tx) | DB::connection($name)->transaction(...) |
| سبک closure | Update(ctx, id, func(*Order) error) (Three Dots Labs) | $repo->update($id, fn (Order $o) => ...) |
| retry هنگام deadlock | حلقهٔ خودتان دور Do | DB::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.Context | ctx = context.WithValue(ctx, txKey{}, tx)؛ repository میخواند | امضا عوض نمیشود؛ repository کوچک میماند | وابستگی پنهان؛ فراموش کردن ctx مشتقشده آسان است |
| repository محدود به tx | repos := postgres.New(tx) برای هر use case | صریح، در زمان کامپایل دیده میشود | factory بهازای هر use case؛ wiring بزرگ میشود |
| update با closure | repository خودش Get، fn شما و Save را در تراکنش خود اجرا میکند | تراکنش نشت نمیکند | فقط به use caseهای load-modify-save میخورد |
Three Dots Labs رویکرد context را آزمایش کرده و میگوید در آزمایشهایشان "a bit magical, not explicit, and slow in some cases" بود و closure را ترجیح میدهد؛ ما رویکرد context را نشان میدهیم چون رابط را کوچک نگه میدارد، و این را صریح میگوییم.
// 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.
کاربر 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، یا ستون سیستمی xmin | xmin با هر بهروزرسانی عوض میشود اما شناسهٔ تراکنش ۳۲ بیتی است و wrap میشود؛ ستون صریح بهتر است |
| MySQL / InnoDB | version عددی یا updated_at با میکروثانیه | updated_at زیر بار برخورد میکند؛ عدد بهتر است |
| SQL Server | ستون rowversion | خودکار، باینری |
| Oracle | ORA_ROWSCN یا ستون version | ستون صریح قابلحمل است |
| MongoDB | findOneAndUpdate با فیلتر {_id, version} | اتمیک بودن تکسند |
| DynamoDB | نوشتن شرطی: ConditionExpression: version = :v | روش استاندارد |
| Redis | WATCH / MULTI / EXEC | ذاتاً خوشبینانه |
| Hibernate / JPA | @Version | خودکار |
| Eloquent | داخلی ندارد | WHERE version را خودتان بگذارید |
| GORM | بهطور پیشفرض داخلی ندارد | gorm.io/plugin/optimisticlock یک plugin است؛ پیش از استفاده مستنداتش را ببینید |
دو قاعده: version فقط در ریشهٔ aggregate است (نه برای هر line)، و repository فقط بعد از موفقیت همهٔ دستورها آن را بالا میبرد.
// 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 + Reconstitute | Go | صریح، کامپایلر بررسی میکند، بدون reflection | فیلدها سه بار فهرست میشوند (struct، snapshot، mapper) |
| فیلدهای exported روی aggregate | Go | بدون نگاشت | هر کسی state را میگذارد؛ invariantها بیمحافظ |
Reflection یا unsafe | Go | بدون نوع snapshot | شکننده، کند، تغییر نام را پنهان میکند |
سازندهٔ خصوصی + reconstitute ایستا | PHP | صریح | همان فهرست سهباره |
ReflectionClass::newInstanceWithoutConstructor + set property | PHP | Doctrine استفاده میکند | همهٔ قواعد را دور میزند؛ mapper تستشده لازم است |
Eloquent hydration (newFromBuilder) | PHP | رایگان | مدل هم aggregate است هم ردیف دیتابیس |
| Serializer (JSON/Symfony Serializer) | PHP | کوتاه | همان دور زدن؛ پیش از اعتماد اعتبارسنجی کنید |
| reconstitution باید | نباید |
|---|---|
همهٔ فیلدها از جمله version را بگذارد | دستورهایی مثل Place را اجرا کند |
| invariantهایی را که ردیف خراب میشکند بررسی کند (status در enum، quantity حداقل ۱) | رویداد OrderPlaced ثبت کند |
| هر بار نمونهٔ تازه برگرداند | نمونهٔ زندهٔ مشترک بین فراخوانها بدهد (خطر کش) |
| روی status ناشناخته بلند شکست بخورد | مقدار ناشناخته را بیصدا پیشفرض کند |
// 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های واقعی است.
تعریف:
| پرسش | ۱. Eloquent خودِ aggregate | ۲. Repository، Eloquent را به دامنه نگاشت میکند | ۳. Repository روی query builder |
|---|---|---|---|
| کلاس دامنه | App\Sales\EloquentAggregate\Order extends Model | App\Sales\Domain\Order (PHP خالص) | App\Sales\Domain\Order (PHP خالص) |
| کلاسهای ماندگاری | هیچ | OrderRecord، OrderLineRecord (Eloquent) | هیچ |
| Repository | هیچ یا finder نازک | EloquentOrderRepository | QueryBuilderOrderRepository |
| تست واحد بدون دیتابیس | خیر (مدل برای save اتصال میخواهد) | بله، با InMemoryOrderRepository | بله، با InMemoryOrderRepository |
| API ماندگاری روی aggregate | عمومی: save، update، delete، fill | پنهان | پنهان |
| relation و eager loading | رایگان: with('lines') | رایگان داخل repository | query دوم را خودتان مینویسید |
| قفل خوشبینانه | با دست: saveWithVersion | داخل save | داخل save |
| رویدادهای مدل / observer | اجرا میشوند (میتوانند غافلگیر کنند) | روی record اجرا میشوند، نه aggregate | هیچ |
| کد نگاشت | هیچ | toDomain و save | hydrate و 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
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 میکند؛ هر پیادهسازی آن را اجرا میکند.
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ها جواب میدهد | ترجمهٔ پرسوجو |
// 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))
}
})
}// 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
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 با کش خودش دارند |
// 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 / Query | repo.Query() یک Builder الکوئنت یا *sql.Rows میدهد | فراخوانها SQL مینویسند؛ تغییر ذخیرهسازی همه را میشکند | aggregate یا DTO برگردانید؛ finder نامدار بیفزایید |
| «Repository» که DAO روی جدول است | یک کلاس برای هر جدول، فقط CRUD | aggregate روی چهار کلاس پخش، بدون invariant | رابط به شکل aggregate |
| منطق کسبوکار در repository | if order.Total > limit داخل Save | قاعدهها از تست دامنه پنهان میماند | به aggregate یا domain service ببرید |
| Repository commit میکند | tx.Commit() داخل Save | use case اتمیک بودن را از دست میدهد | سرویس برنامه مالک تراکنش است |
| Repository aggregate نیمهبارشده میدهد | lineها تا لمس نشوند nil | invariantها روی state ناقص بررسی میشوند | کامل بارگذاری کنید، یا proxy تنبل که کامل رفتار کند |
| Repository context دیگر را صدا میزند | SalesOrderRepository از catalog_products میخواند | اتصال بین contextها | Catalog API یا کپی خواندنی محلی |
| Active Record پنهان | متد دامنه save() صدا میزند | دامنه به ماندگاری وابسته است | repository ذخیره میکند، aggregate هرگز |
| Save از هر جا | controllerها $repo->save() میزنند | invariantها نادیده میمانند | سرویس برنامه تنها فراخوان است |
// 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
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 قدمبهقدم حیاتی
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 کنید |
| نقض unique | PostgreSQL SQLSTATE 23505؛ MySQL خطای 1062؛ هر دو یعنی دیگری زودتر id را درج کرده |
| شکست serialisation | 40001 زیر REPEATABLE READ یا SERIALIZABLE: تراکنش را دوباره اجرا کنید، Isolation Levels |
| Deadlock | 40P01 (PostgreSQL)، 1213 (MySQL): retry؛ DB::transaction(..., attempts: n) در Laravel این را انجام میدهد |
| انتظار قفل | MySQL 1205؛ PostgreSQL با lock_timeout خطای 55P03 میدهد |
| cascade کلید خارجی | ON DELETE CASCADE روی order_lines Remove را یک دستور میکند |
Get قدمبهقدم حیاتی
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) | درایور و جعبهابزار PostgreSQL | pgx.Tx، pgxpool.Pool، Exec، Query، QueryRow |
sqlc | از فایل SQL کد Go ایمن از نظر نوع تولید میکند | یک متد تولیدی برای هر query؛ رابط DBTX با pool یا tx کار میکند؛ WithTx |
| GORM | ORM | db.Transaction(func(tx *gorm.DB) error)؛ تراکنش پیشفرض نوشتن را میشود با SkipDefaultTransaction خاموش کرد |
| ent | فریمورک entity با codegen | client.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 تور ایمنی است.
-- 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 آن
// 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
}رابط در دامنه مینشیند
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
// 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
}// 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
}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);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() })
}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 بدون دیتابیس
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؛ بستهٔ Postgressalesرا 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
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
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
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
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
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
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
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
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
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
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
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 | ستون version | UPDATE ... WHERE version = $loaded | قفلی نگه نمیدارد | retry هنگام تعارض |
| aggregate نیمهذخیره | یک تراکنش برای هر use case | UnitOfWork.Do، DB::transaction | aggregate و outbox اتمیک | wiring تراکنش |
| تست دامنهٔ کند | fake درونحافظه + contract test | memory.New() | میلیثانیه، همچنان صادق | نگهداری fake |
| N+1 هنگام load | دو query، = ANY / whereIn | lineهای همهٔ idها یکجا | تعداد query ثابت | نگاشت با id |
| منطق پرسوجوی تکراری | Specification | UnpaidLongerThan | قاعدهٔ نامدار، تست درونحافظه | یک شاخهٔ مترجم برای هر spec |
| لیستها دنیا را load میکنند | Query service / read model | query DTO تخت | سریع، صفحهبندیشده | مسیر خواندن دوم |
| دامنه به Eloquent وابسته است | گزینهٔ ۲ یا ۳ | OrderRecord + mapper | دامنهٔ خالص | کد نگاشت |
| کش کهنه | decorator با باطلسازی | کش snapshot، با Save باطل | خواندن سریعتر | پیچیدگی |
| رویداد شبح یا گمشده | ردیف outbox در Save | همان تراکنش | انتشار at-least-once | process relay |
گذار از دروازهٔ جدول به repository، قدمبهقدم
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(...) در controller | finder نامدار یا 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 یا sqlc | fake + contract test | بدون change tracking، SQL صریح |
| تیم روی Hibernate، Doctrine یا EF | collection-oriented روی unit of work خود ORM | باز هم یک repository برای هر ریشه | ORM از قبل دنبال میکند |
| مسیر خواندن داغ | query service با DTO تخت | کش، صفحهبندی keyset | aggregate برای دستور است |
| ردیف داغ نوشتن (شمارندهٔ موجودی) | lockForUpdate یا UPDATE اتمیک داخل repository | ستون version بهعنوان پشتیبان | retryهای خوشبینانه روی یک ردیف میچرخند |
| aggregate با event sourcing | repository رویدادها را میخواند و بازسازی میکند | snapshot | state همان جریان رویداد است |
| گزارش بین contextها | read model یا warehouse | CDC | هرگز repository بین contextها |
| aggregate بزرگ (صدها فرزند) | مرز را بازنگری کنید | aggregateهای کوچکتر، ارجاع با id | load کامل مقیاس نمیگیرد |
| schema قدیمی جدولها | گزینهٔ ۳ یا persistence model | view، 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ها در repository | Fulfilment order_id را بهعنوان id نگه میدارد، نه کلید خارجی به sales | contextها بعداً قابل جدا شدن میمانند |
| خواندن بین 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).
مثال تولیدی: سفارش ثبت شد -> محموله ساخته شد (دو سرویس، دو دیتابیس)
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 موجودی یا کپی خواندنی محلی |
| تغییر اتمیک چندسرویسی | تراکنش توزیعشده در Save | Saga (Saga Pattern) |
دادههای توزیعشده: replica، کش و چندمنطقهای
| وضعیت | اثر روی repositoryها | راهکار |
|---|---|---|
| Read replica | Get از replica ممکن است کهنه باشد، سپس Save روی version تعارض میکند | مسیر دستور از primary میخواند؛ queryهای لیست از replica (Replication & Failover) |
کش جلوی Get | aggregate کهنه | کش 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 برای query | query service ظاهر میشود |
| ۱۰۰× | decorator کش snapshot روی aggregateهای داغ، جدولهای partitionشده، shard بهازای tenant، outbox با CDC | مرز aggregateها بازنگری میشود؛ ردیفهای داغ UPDATE اتمیک یا قفل بدبینانه میگیرند |
| فراتر | aggregateهای event-sourced برای پرکارترینها، snapshot هر N رویداد | پیادهسازی متفاوت پشت همان رابط |
آزمایشگاه: یک contract، سه پیادهسازی
Expected, not run: قدمهای Postgres دیتابیس میخواهند؛ قدمهای درونحافظه اجرا شدند.
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 هم پاس میشوند آزمایشها
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 شکست میخورد-- 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 root | entityای که aggregate از طریق آن در دسترس است و عوض میشود |
| Collection-oriented repository | repository با Add/Remove بدون save؛ به change tracking تکیه دارد |
| Persistence-oriented repository | repository با 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 کهنه |
منابع
- Eric Evans, Domain-Driven Design Reference, 2015: Repositories. Saved:
domainlanguage-ref.txt - Edward Hieatt and Rob Mee, Repository (PoEAA), 5 March 2003. Saved:
fowler-repository.txt - Eric Evans and Martin Fowler, Specifications. Saved:
fowler-spec.txt - Martin Fowler, Unit of Work and DDD Aggregate. Saved:
fowler-uow.txt,fowler-agg.txt - Vaughn Vernon, Implementing Domain-Driven Design, ch. 12 Repositories: paraphrased from a search-result summary only (page returned 403). Saved:
vernon-ch12-secondary.txt. Vernon, Effective Aggregate Design. Saved:vernon-effective-agg.txt - Vlad Khononov, Learning Domain-Driven Design (2021): background only, not fetched, nothing quoted
- Microsoft, Infrastructure persistence layer design. Saved:
ms-repo.txt - Three Dots Labs, The Repository pattern in Go and DDD Lite in Go. Saved:
threedots-repo.txt,threedots-ddd-lite.txt - Laravel 13 docs: Eloquent, Database: transactions, Query builder, Database testing. Saved:
laravel-*.txt - Go: pgx README, sqlc README, GORM transactions, ent transactions. Saved:
pgx-readme.md,sqlc-readme.md,gorm-tx.txt,ent-tx.txt