Domain, Application & Infrastructure Services
"When a significant process or transformation in the domain is not a natural responsibility of an entity or value object, add an operation to the model as a standalone interface declared as a service." — Eric Evans، Domain-Driven Design Reference (۲۰۱۵)، بخش "Services"
خلاصه (Summary): در یک کد DDD واژهٔ «سرویس (Service)» سه چیز متفاوت است. سرویس دامنه (Domain service) قاعدهای کسبوکاری را نگه میدارد که مال هیچ entity تنهایی نیست. سرویس کاربردی (Application service) یک use case را از اول تا آخر اجرا میکند، بیآنکه خودش چیزی تصمیم بگیرد. سرویس زیرساخت (Infrastructure service) یک توانایی فنی است پشت interfaceی که لایههای داخلی صاحبش هستند. قاطی کردن این سه همان راهی است که قاعدهٔ کسبوکار سر از controller درمیآورد و SQL سر از مدل. تمرکز (Focus): سه نوع سرویس و مسئولیت دقیق هر کدام، قاعدهٔ وابستگی (Dependency rule)، port و adapter، ریشهٔ ترکیب (Composition root)، command handler و query handler (CQS)، تراکنش و unit of work، رویداد دامنه که بعد از commit پخش میشود، دغدغههای سراسری به شکل decorator، DTO و اعتبارسنجی در لبه، ضدالگوها (application service چاق، domain service بهعنوان انباری، پسوند «Service» روی همهچیز، Eloquent یا DB در دامنه، facade ایستا در مدل)، و یک use case واحد به نام PlaceOrder که سرتاسر در Go و Laravel 13 همراه با تست ساخته میشود. هدف یادگیری (Learning goal): برای هر قاعده یا خط کد در یک سیستم سفارش بتوانید بگویید مال کدام لایه است و چرا. یک use case نازک بنویسید که بار میکند، تصمیم را به دامنه میسپارد، ذخیره میکند و رویداد را در یک تراکنش منتشر میکند. هر سیستم بیرونی را پشت portی بگذارید که داخل تعریفش کرده، و هر نوع سرویس را با ارزانترین تستی بسنجید که هنوز چیزی را ثابت میکند.
این فصل در گروه DD 02 (طراحی تاکتیکی) است. بعد از Entities & Value Objects، Aggregates & Factories، Anemic vs Rich Domain Models و Repositories میآید و از هر چهار استفاده میکند. پرسشی که این صفحه صاحبش است: کدام کد در کدام نوع سرویس مینشیند و این سرویسها چطور به هم وابستهاند؟ بقیه را همسایهها میگویند. رویداد دامنه چیست و چه فرقی با رویداد یکپارچهسازی دارد: Domain Events vs Integration Events. relay در outbox چطور منتشر میکند: Outbox Pattern. مقایسهٔ سبکهای لایهای، hexagonal، onion و clean بهعنوان معماری: Layered Monolith. اصلی که زیر portها خوابیده: Dependency Inversion Principle. تقسیم مسئولیت میان کلاسها بهطور کلی: Low-Level Design و Object-Oriented Modeling. طراحی ماندگاری پشت port مخزن: Data Persistence Design. مثال جاری همان کسبوکار سفارش آنلاین و ارسال است که در کل مسیر DDD دنبال میکنیم. contextهایش Sales، Fulfilment، Billing، Catalog و Identity هستند و use case این صفحه PlaceOrder در Sales است.
نقشهٔ صفحه (Page map)
| دنبال چه هستید | بروید به |
|---|---|
| کل صفحه در چهار جدول | همهچیز در یک دقیقه |
| چرا یک واژه سه معنا لازم دارد | چرا سه نوع سرویس وجود دارد |
| Evans، Fowler/Stafford، Cockburn، Martin، Vernon، Three Dots | از کجا آمده |
| قیمتگذاری روی سطرها، سطح مشتری و تخفیفها | سرویس دامنه |
| بار کن، تصمیم بگیر، ذخیره کن، منتشر کن | سرویس کاربردی / use case |
| درگاه پرداخت، ساعت، ایمیل، فضای فایل | سرویس زیرساخت |
| interface در داخل، پیادهسازی در بیرون | قاعدهٔ وابستگی، port و adapter |
| command تغییر میدهد، query جواب میدهد | command handler و query handler |
| تراکنش کجا زندگی میکند | تراکنش و unit of work |
| در aggregate ثبت، بعد از commit پخش | رویداد دامنه از دل use case |
| لاگ، متریک، مجوز، idempotency | دغدغههای سراسری به شکل decorator |
| Form Request، command DTO، result DTO | DTO و اعتبارسنجی در لبه |
OrderService، OrderManager، OrderHelper | نامگذاری: پسوند «Service» |
| چرخهٔ درخواست، SQL، کدهای خطا | سازوکار |
PlaceOrder سرتاسر با تست | Go، Laravel |
| سرویس چاق، نشت Eloquent، facade در مدل | حل مسئلههای کلاسیک |
| 15 قاعده که در لایهها جا داده شدهاند | انتخاب: این منطق کجا برود؟ |
| از monolith تا دادهٔ توزیعشده | در معماری |
| تمرین عملی | آزمایشگاه |
| باورهای غلط، چکیده، آزمون، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
سه نوع سرویس. هر سطر در فهرست مفاهیم باز میشود.
| نوع | به زبان ساده | مثال در Sales | state دارد؟ | I/O دارد؟ | جایش |
|---|---|---|---|---|---|
| سرویس دامنه (Domain service) | قاعدهای کسبوکاری که مال هیچ entity یا value object تنهایی نیست | PricingService.Quote(order, tier, promotions) | نه | نه | لایهٔ دامنه |
| سرویس کاربردی (Application service، use case، interactor، command handler) | یک هدف کاربر را اجرا میکند: بار کن، از دامنه بپرس، ذخیره کن، منتشر کن | PlaceOrderHandler.Handle(PlaceOrder) | نه (فقط پیشرفت همان فراخوانی) | فقط از راه port | لایهٔ کاربرد |
| سرویس زیرساخت (Infrastructure service) | توانایی فنیای که برای کسبوکار مهم نیست چطور انجام شود | StripePaymentGateway، SystemClock، mailer روی SMTP | ممکن است client و pool نگه دارد | بله، کارش همین است | زیرساخت (adapterها) |
قاعدهٔ وابستگی و اجزایش:
| اصطلاح | به زبان ساده | در این فصل |
|---|---|---|
| قاعدهٔ وابستگی (Dependency rule) | کد منبع فقط رو به داخل اشاره میکند؛ دامنه چیزی از بیرون import نمیکند | sales نه database/sql را import میکند، نه net/http، نه facade لاراول |
| Port | interfaceی که مال داخل است و با زبان خود داخل نوشته شده | OrderRepository، PaymentGateway، Clock، Outbox |
| Adapter | پیادهسازی یک port با یک فناوری مشخص | postgres.Orders، stripe.Gateway، EloquentOrderRepository |
| adapter راننده (Driving / primary) | برنامه را صدا میزند | HTTP handler، Form Request + controller، job صف، CLI، تست |
| adapter راندهشده (Driven / secondary) | برنامه صدایش میزند | دیتابیس، درگاه پرداخت، broker، ساعت |
| ریشهٔ ترکیب (Composition root) | تنها جایی که adapterها را به portها وصل میکند | cmd/shop/main.go، SalesServiceProvider |
command در برابر query در لایهٔ کاربرد:
| Command handler | Query handler | |
|---|---|---|
| هدف | تغییر state برای یک use case | برگرداندن داده برای یک صفحه یا API |
| aggregate بار میکند؟ | بله، از راه repository | نه، مستقیم از view یا جدول میخواند |
| تراکنش | بله، یکی برای هر command | معمولاً نه، یا فقطخواندنی |
| رویداد میسازد | بله، از راه aggregate | هرگز |
| خروجی | هیچ یا یک result DTO کوچک (id، مبلغ) | DTOی همشکل نیاز خواننده |
| با چه مقیاس میگیرد | دیتابیس اصلی | replica، cache، projection (CQRS) |
ضدالگو ← نشانه ← درمان (جزئیات در حل مسئلههای کلاسیک):
| ضدالگو | نشانه | درمان |
|---|---|---|
| application service چاق | if tier == "gold" داخل PlaceOrderHandler | قاعده را به aggregate یا یک domain service ببرید |
| domain service بهعنوان انباری | OrderDomainService با 40 متد بیربط | یک سرویس برای هر عملیات نامدار؛ بیشترشان به entity برمیگردند |
| پسوند «Service» روی همهچیز | OrderService و OrderManager و OrderHelper کنار هم | عملیات را با زبان فراگیر نام بگذارید: PricingService، PlaceOrder |
| زیرساخت در دامنه | Order::where(...) یا DB::table در کلاس دامنه | port مخزن در دامنه، Eloquent در adapter |
| facade ایستا در مدل | Cache::remember، now()، Mail:: داخل Order | مقدار را ورودی بدهید، یا port را به application service تزریق کنید |
| فراخوانی بیرونی داخل تراکنش | صدا زدن Stripe بین BEGIN و COMMIT | بیرون صدا بزنید، در شکست جبران کنید، کلید idempotency بگذارید |
| انتشار رویداد پیش از commit | Fulfilment سفارشی را ارسال میکند که rollback شده | سطر outbox در همان تراکنش، یا ShouldDispatchAfterCommit |
چرا سه نوع سرویس وجود دارد
واژهٔ «سرویس» دستکم از سه طرف وارد کد میشود. Evans آن را برای عملیاتی از دامنه به کار میبرد که خانهٔ طبیعی ندارد. کتاب Patterns of Enterprise Application Architecture فاولر (فصلی که Randy Stafford نوشته) Service Layer را برای مرز برنامه به کار میبرد. هر فریمورکی هم آن را برای «کلاسی که یک client داخلش است» به کار میبرد: mail service، cache service، payment service. اگر تیم این سه را از هم جدا نکند، یک کلاس به نام OrderService هر سه کار را برمیدارد. تخفیف را حساب میکند، تراکنش باز میکند، Stripe را صدا میزند، SQL مینویسد و JSON را قالب میدهد. هیچ چیزش بدون دیتابیس و شبکه تست نمیشود و هیچ قاعدهای از آن را نمیشود در worker صف یا CLI دوباره به کار برد.
تقسیم بر اساس نوع دانشی است که کد نگه میدارد:
| سه نوع را جدا نگه داریم | یک «سرویس» همهکار |
|---|---|
| قاعدهٔ قیمتگذاری یکجا عوض میشود و در چند میلیثانیه تست میشود | قاعده در controller و job ورود داده و پنل ادمین کپی شده |
| use case مثل خود user story خوانده میشود: بار کن، ثبت کن، ذخیره کن، منتشر کن | use case دویست خط SQL و if و فراخوانی HTTP است |
| با نوشتن یک adapter میشود Stripe را با Adyen عوض کرد | نام فیلدهای Stripe در سراسر دامنه پخش است |
| همان use case از HTTP، صف، CLI یا تست اجرا میشود | هر نقطهٔ ورود جریان را از نو پیاده میکند |
| از اول فایل و interface بیشتر | فایل کمتر، تا وقتی نقطهٔ ورود دوم برسد |
| مناسب: دامنههای اصلی با قاعدهٔ واقعی (Domains & Subdomains) | قابل قبول: CRUD عمومی که قاعدهای برای محافظت ندارد |
تشبیهی که در این صفحه بارها برمیگردد: یک رستوران. قضاوت سرآشپز همان دامنه است. دستور پخت و قاعدهای مثل «این میز تخفیف منوی ویژه میگیرد چون هشت نفرند و امروز سهشنبه است» به چند چیز با هم وابسته است و به هیچ چیز بیرون از آشپزخانه وابسته نیست. آن قضاوت یک domain service است. هماهنگکنندهٔ پیشخوان (expediter) application service است. سفارش را میگیرد، ایستگاهها را به ترتیب صدا میزند، کامل بودن بشقاب را بررسی میکند، آن را بیرون میفرستد و سفارش را بستهشده علامت میزند. خودش چیزی نمیپزد و هیچ دستور پختی را تعیین نمیکند. کارتخوان، ون تأمینکننده و ماشین ظرفشویی سرویسهای زیرساختاند. رستوران به آنها نیاز دارد، ولی با عوض شدن بانک، منو عوض نمیشود. قاعدهٔ وابستگی میگوید کتاب دستور پخت هیچوقت اسمی از بانک نمیبرد.
تصویر سه حلقه را نشان میدهد. در مرکز، دامنه است: aggregate Order، domain service PricingService و port OrderRepository که خود دامنه تعریفش کرده. حلقهٔ میانی لایهٔ کاربرد است: use case PlaceOrderHandler و portهایی که لازم دارد (PaymentGateway، Clock، Catalog، Outbox). حلقهٔ بیرونی زیرساخت است با adapterهایش: Stripe، ساعت سیستم، repository پستگرس، HTTP handler و job صف. همهٔ پیکانهای کد منبع رو به داخلاند. پیکان خطخورده از دامنه به database/sql همان جهتی است که قاعدهٔ وابستگی ممنوع میکند.
سه بدفهمی رایج، از همین اول
- «در DDD منطق کسبوکار در domain service میرود.» بیشتر منطق کسبوکار روی entity و value object مینشیند. معیار Evans این است: «not a natural responsibility of an entity or value object». domain service استثناست، نه پیشفرض. بیرون کشیدن قاعدهها از entity و ریختنشان در سرویس دقیقاً همان مدل دامنهٔ کمخون (Anemic) را میسازد.
- «application service همان لایهٔ کسبوکار است.» فاولر در خلاصهٔ لایههای Evans میگوید لایهٔ کاربرد «does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down.» اگر دامنه را پاک کنید و application service هنوز قیمت حساب کند، قاعده جای غلطی است.
- «زیرساخت یعنی دیتابیس.» زیرساخت هر توانایی فنی است: درگاه پرداخت، ایمیل، پیامک، ساعت، تولید عدد تصادفی و شناسه، فضای فایل، feature flag، API سرویسهای دیگر. ساعت بیش از همه گول میزند:
time.Now()یاnow()داخل دامنه یک فراخوانی زیرساختی است.
از کجا آمده
Fowler و Stafford، ۲۰۰۲ تا ۲۰۰۳: Service Layer. در Patterns of Enterprise Application Architecture فصلی هست به قلم Randy Stafford (مدخل کاتالوگ تاریخ ۵ مارس ۲۰۰۳ دارد). الگو را اینطور تعریف میکند: "A Service Layer defines an application's boundary and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coor-dinating responses in the implementation of its operations." جملهٔ آخر میگوید service layer منطق کسبوکار را در بر میگیرد. در DDD همین لایه فقط هماهنگ میکند و منطق را به دامنه میسپارد. این دو سنت عمداً با هم فرق دارند: service layer در PoEAA میتواند خودش منطق را نگه دارد، ولی application service در DDD باید آن را واگذار کند.
Evans، ۲۰۰۳: نامگذاری سه نوع. کتاب Domain-Driven Design (Addison-Wesley، ۲۰۰۳) بلوک سازندهٔ Services و الگوی Layered Architecture را معرفی کرد. کتاب سرویسهای کاربردی، دامنه و زیرساخت را از هم جدا میکند (ما با DDD Reference رایگان کار کردیم، نه با خود کتاب). Reference (۲۰۱۵) تعریف بالای همین صفحه را نگه میدارد و اضافه میکند: "Define a service contract, a set of assertions about interactions with the service... State these assertions in the ubiquitous language of a specific bounded context. Give the service a name, which also becomes part of the ubiquitous language." مدخل Layered Architecture آن میگوید: "Isolate the expression of the domain model and the business logic, and eliminate any dependency on infrastructure, user interface, or even application logic that is not business logic"، و همانجا به hexagonal architecture بهعنوان جایگزینی اشاره میکند که "may serve as well or better".
Fowler، ۲۰۰۳: هشدار کمخونی. مقالهٔ AnemicDomainModel (۲۵ نوامبر ۲۰۰۳) توصیف لایههای Evans را نقل میکند، از جمله "This layer is kept thin"، و ضدالگو را "really just a procedural style design" مینامد.
Cockburn، ۲۰۰۵: port و adapter. گزارش فنی Hexagonal (Ports & Adapters) Architecture از Alistair Cockburn (تاریخ ۴ سپتامبر ۲۰۰۵) نیتش را اینطور میگوید: "Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases." ششضلعی لایه ندارد. یک داخل دارد، یک بیرون، و portهایی میانشان.
Meyer و Fowler: CQS. جداسازی command و query از Bertrand Meyer، به خلاصهٔ فاولر در CommandQuerySeparation (۵ دسامبر ۲۰۰۵): "Queries: Return a result and do not change the observable state of the system... Commands: Change the state of a system but do not return a value." بعدها Greg Young این ایده را از سطح متد به سطح مدل برد و CQRS شد (ببینید Event Sourcing & CQRS).
Martin، ۲۰۱۲: قاعدهٔ وابستگی و use caseها. مقالهٔ The Clean Architecture از Robert C. Martin (۱۳ اوت ۲۰۱۲) نامش را میگذارد: "The Dependency Rule. This rule says that source code dependencies can only point inwards." حلقهٔ use case او "contains application specific business rules... These use cases orchestrate the flow of data to and from the entities." «interactor» او همان application service در زبان Evans است.
Vernon، ۲۰۱۳، و Khononov، ۲۰۲۱. کتاب Implementing Domain-Driven Design از Vaughn Vernon یک فصل کامل (فصل ۷) به domain serviceها میدهد و application serviceها را در فصل ۱۴ پوشش میدهد. کتاب Learning Domain-Driven Design از Vlad Khononov (O'Reilly، ۲۰۲۱) همین کار را در فصلهای الگوهای منطق کسبوکار و الگوهای معماری میکند. هنگام نوشتن این صفحه هیچکدام از این دو کتاب را باز نداشتیم. فقط برای جهتیابی به آنها ارجاع میدهیم و چیزی از آنها نقل نمیکنیم.
Three Dots Labs، ۲۰۲۰: شکل Go. مقالهٔ Miłosz Smółka با عنوان Introducing Clean Architecture by refactoring a Go project (۱ سپتامبر ۲۰۲۰) و مقالهٔ Robert Laszczak با عنوان How to use basic CQRS in Go (۲۸ سپتامبر ۲۰۲۰) مثال Wild Workouts را به domain، app/command، app/query، adapters و ports بازآرایی میکنند. تعریفشان از لایهٔ میانی: "application logic is a thin layer that 'glues together' other layers. It's also known as 'use cases'." مقالهٔ CQRS هم "leads to splitting application services into two separate types: command and query handlers."
Year Source What it added to "service"
1 2002 Fowler/Stafford, PoEAA Service Layer Application boundary; transactions live here
2 2003 Evans, DDD (book) Domain vs application vs infrastructure services
3 2003 Fowler, AnemicDomainModel Application layer is thin; rules stay in the domain
4 2005 Cockburn, Hexagonal Ports owned by the inside; adapters outside
5 2005 Fowler on Meyer's CQS Commands change, queries answer
6 2008 Palermo, Onion Architecture Same rule, drawn as rings
7 2012 Martin, Clean Architecture Dependency rule; use cases / interactors
8 2013 Vernon, IDDD (ch. 7, 14) Domain and application services in practice
9 2015 Evans, DDD Reference The definitions quoted on this page
10 2020 Three Dots Labs, Wild Workouts Go layout: domain, app/command, app/query, adapters, portsفهرست مفاهیم
ده بلوک. چهار بلوک اول هستهٔ بحثاند. بقیه سازوکارهاییاند که هر use case واقعی لازم دارد.
سرویس دامنه (Domain service) حیاتی
به زبان ساده: سرویس دامنه یک محاسبه یا تصمیم کسبوکاری است که همزمان به چند شیء دامنه نیاز دارد و برای همین درون هیچکدامشان جا نمیشود. همانطور نامگذاری میشود که کسبوکار نامش را میبرد، state نگه نمیدارد و به دیتابیس و شبکه و ساعت دست نمیزند.
بدفهمی رایج: «هر aggregate یک XxxDomainService کنار خودش لازم دارد.» نه. اگر قاعده فقط دادهٔ خود سفارش را لازم دارد، متدی روی Order است، و بردنش به سرویس entity را کمخون میکند. domain service فقط وقتی موجه است که عملیات روی چند aggregate یا value object پخش باشد، یا گذاشتنش روی یکی از آنها دلبخواهی باشد. مثال کلاسیک: انتقال وجه مال حساب مبدأ است یا حساب مقصد؟ مال هیچکدام.
تعریف: عملیاتی بیحالت (Stateless) در لایهٔ دامنه که با زبان فراگیر (Ubiquitous language) بیان میشود و فرایند یا تبدیل مهمی از دامنه را پیاده میکند که مسئولیت طبیعی هیچ entity یا value objectی نیست. ورودی و خروجیاش اشیای دامنهاند و قراردادی (پیششرط و پسشرط) دارد که به زبان یک bounded context بیان میشود. I/O ندارد. اگر به دادهای از بیرون نیاز داشته باشد، application service اول آن داده را میآورد و به آن میدهد.
Who What happens Layer
1 PlaceOrderHandler has: order (3 lines), tier=gold, promotions=[MUG3] application
2 PlaceOrderHandler calls pricing.Quote(order, gold, [MUG3]) application -> domain
3 PricingService subtotal = sum(unit price x qty) domain
4 PricingService MUG3: 5 mugs >= 3, so 10% off that line domain
5 PricingService gold: 5% off what remains after promotions domain
6 PricingService net >= 50.00, so shipping is free domain
7 PricingService returns Quote{subtotal, discount, shipping, total} domain -> application
8 PlaceOrderHandler order.Place(quote, paymentRef, now) application -> domainسناریوهای واقعی:
- قیمتگذاری (همین فصل): سطرها + سطح مشتری + تخفیفهای فعال + سیاست هزینهٔ ارسال. هیچ شیء تنهایی مالک هر چهار نیست.
- انتقال وجه در کیف پول: برداشت از یک حساب، واریز به حساب دیگر، اعمال سیاست کارمزد. مثال کلاسیک Evans و Vernon.
- تخصیص در Fulfilment: انتخاب انبار برای هر سطر سفارش بر اساس موجودی، فاصله و ساعت تحویل به پیک.
- سیاست overbooking در سیستم رزرو: آیا این رزرو بار میتواند تا ده درصد از ظرفیت سفر بیشتر شود؟
- محاسبهٔ مالیات روی سطرها و آدرس ارسال، وقتی قاعدهها مال خودتان است نه API یک فروشنده. اگر API فروشنده باشد، سرویس زیرساخت پشت یک port است.
جایش در هر stack:
| Stack | شکل | سیمکشی |
|---|---|---|
| Go | struct ساده با متد خالص در پکیج دامنه (sales.PricingService)؛ عددهای سیاست بهصورت فیلد | در main بهصورت مقدار ساخته میشود؛ تا وقتی گونههای مختلف ندارد interface لازم نیست |
| Laravel 13 | final readonly class در app/Modules/Sales/Domain، بدون facade و Eloquent | $this->app->singleton(PricingService::class, ...) با مقادیر config |
| Java / Spring | کلاس ساده؛ @Service یک stereotype اسپرینگ است، نه یک نوع DDD | روی domain service @Transactional نگذارید |
| .NET | کلاس در پروژهٔ Domain، بدون ارجاع به EF Core | در Program.cs ثبت میشود؛ پروژهٔ دامنه به چیزی ارجاع نمیدهد |
درمان / طرز استفاده: خالص نگهش دارید و با یک جدول تستش کنید، مثل Go و Laravel. اگر وسوسه شدید repository را به domain service تزریق کنید، دست نگه دارید. یا application service داده را بار میکند و به آن میدهد، یا دامنه یک port باریک تعریف میکند (مثلاً ExchangeRates) و میپذیرید که این سرویس دیگر خالص نیست. این را در نام و تستهایش هم صادقانه نشان بدهید.
سرویس کاربردی / use case (Application service) حیاتی
به زبان ساده: برای هر کاری که کاربر یا سیستم میخواهد انجام شود یک کلاس (یا تابع) دارید: «سفارش ثبت کن»، «سفارش لغو کن»، «پرداختشده علامت بزن». مثل user story خوانده میشود. چیزهای لازم را میآورد، تصمیم را از دامنه میخواهد، نتیجه را ذخیره میکند و اتفاق را منتشر میکند. خودش هیچ تصمیمی نمیگیرد.
بدفهمی رایج: «نازک یعنی سه خط.» نازک یعنی بدون قاعدهٔ کسبوکار، نه کمخط. PlaceOrderHandler حدود شصت خط است: بررسی idempotency، خواندن از سه port، گرفتن مجوز پرداخت بیرون از تراکنش، یک جبران، یک تراکنش. همهاش هماهنگسازی (Orchestration) است. حتی یک خطش هم قیمت حساب نمیکند یا تعداد را نمیسنجد.
تعریف: شیئی بیحالت در لایهٔ کاربرد که یک use case را پیاده میکند. یک input DTO (همان command) میگیرد که مجوز و شکلش در لبه بررسی شده. aggregateها را از راه repository بار میکند، رفتار دامنه (entityها و domain serviceها) را صدا میزند، aggregate تغییرکرده را در یک تراکنش ذخیره میکند، رویدادهای دامنهای را که جمع کرده پخش میکند و یک output DTO یا هیچ برمیگرداند. خلاصهٔ فاولر از Evans: "Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems." نامهای دیگرش: use case یا interactor (Martin)، command handler (واژگان CQRS و Wild Workouts)، Action (جامعهٔ لاراول)، application service (Evans و Vernon).
Step PlaceOrderHandler.Handle(cmd) Kind of work
1 1 orders.Get(cmd.OrderID): exists? return replay idempotency (application)
2 2 catalog.UnitPrices, customers.Tier, promotions.Active gather inputs via ports
3 3 sales.NewOrder(...) domain: invariants
4 4 pricing.Quote(order, tier, promos) domain service
5 5 payments.Authorize(key, total) infrastructure, OUTSIDE the tx
6 6 order.Place(quote, ref, now) domain: state change + OrderPlaced
7 7 uow.Do: orders.Add(order); outbox.Append(events) one transaction
8 8 on failure: payments.Void(ref) compensation
9 9 return PlaceOrderResult{OrderID, Total} output DTOسناریوهای واقعی: PlaceOrder، CancelOrder، MarkOrderPaid (با رویداد Billing)، ReserveStock، ScheduleShipment، RefundPayment، ChangeShippingAddress. در همهشان قدمها یکی است: بار کن، تصمیم بگیر، ذخیره کن، منتشر کن. فقط فراخوانی دامنه در وسط فرق میکند.
دانهبندی: یک کلاس برای هر use case یا یکی برای هر aggregate؟
| سبک | شکل | خوبی | مراقب باشید |
|---|---|---|---|
| یک handler برای هر use case | PlaceOrderHandler، CancelOrderHandler | کوچک، یک دلیل برای تغییر (SRP)، decorate کردنش ساده | فایل زیاد؛ helper مشترک را کم نگه دارید |
| یک سرویس گروهی برای هر aggregate | OrderApplicationService با place() و cancel() | فایل کمتر، سبک IDDD ورنون | به god service تبدیل میشود؛ constructor همهٔ وابستگیها را جمع میکند |
Action لاراول (lorisleiva/laravel-actions) | یک کلاس، handle() بهعلاوهٔ asController و asJob | یک کلاس هم controller است، هم job، هم listener | use case را به پکیج گره میزند؛ فراخوانی دامنه را داخل handle() نگه دارید |
| تابع | func PlaceOrder(deps, cmd) | در Go کمینه | وابستگیها به شکل آرگومان میآیند؛ decorator سختتر است |
درمان / طرز استفاده: handler در Go و handler در Laravel را ببینید. آزمون بازبینی: فقط application service را بخوانید. اگر از رویش بفهمید مشتری طلایی چقدر تخفیف میگیرد، یک قاعده نشت کرده.
سرویس زیرساخت (Infrastructure service) حیاتی
به زبان ساده: چیزی که سیستم لازم دارد و ربطی به قاعدههای کسبوکار ندارد: کارت را شارژ کن، ایمیل بفرست، ساعت را بگو، شناسه بساز، فایل نگه دار، API یک شرکت دیگر را صدا بزن. داخل سیستم نیازش را به شکل interface توصیف میکند و بیرون آن را فراهم میکند.
بدفهمی رایج: «PaymentService سرویس دامنه است، چون پرداخت بخشی از کسبوکار ماست.» قاعدهٔ «سفارش پیش از ارسال باید پرداخت شده باشد» مال دامنه است. حرف زدن با Stripe زیرساخت است. port با کلمات use case نامگذاری میشود (Authorize، Void) و adapter با کلمات Stripe حرف میزند (PaymentIntent، capture_method=manual، Idempotency-Key).
تعریف: یک توانایی فنی که در لایهٔ زیرساخت به شکل adapter پشت یک port پیاده شده. port (interface) را لایهای اعلام میکند که به آن نیاز دارد: دامنه برای repositoryها، و لایهٔ کاربرد برای gateway و ساعت و outbox. adapter در ریشهٔ ترکیب انتخاب میشود. سرویس زیرساخت ممکن است stateی نگه دارد که ربطی به کسبوکار ندارد: client HTTP، pool اتصال، کلید API، سقف تلاش مجدد.
Inside (port owner) Port Adapter (infrastructure) Test double
1 application: PlaceOrder PaymentGateway stripe.Gateway (HTTP, form body) memory.Payments
2 application: PlaceOrder Clock clock.System (time.Now().UTC()) memory.FixedClock
3 domain: Sales OrderRepository postgres.Orders (database/sql) memory.Store
4 application: PlaceOrder Outbox postgres.Outbox (INSERT outbox) memory.Store
5 application: PlaceOrder Catalog local price list / HTTP client memory.Catalog
6 application: SendReceipt Mailer SMTP / SES / Postmark array of sent mailsسناریوهای واقعی: درگاه پرداخت (Stripe، Adyen، PayPal)، ایمیل و پیامک (SES، Postmark، Twilio)، فضای ذخیرهٔ شیء (S3، GCS)، تولید شناسه (UUIDv7، Snowflake؛ ببینید ID Generation)، ساعت، feature flag، geocoding، فروشندهٔ نرخ مالیات، ساخت PDF، و bounded contextهای دیگر که روی HTTP صدا زده میشوند. مورد آخر پشت یک لایهٔ ضدفساد (Anticorruption layer) مینشیند (Context Maps).
در هر stack:
| توانایی | adapter در Go | adapter در Laravel 13 | جایگزین در تست |
|---|---|---|---|
| HTTP API (Stripe) | client در net/http با timeout | Http::withToken()->asForm()->post() | httptest.Server / Http::fake() |
| ساعت | time.Now().UTC() | Date::now() | ساعت ثابت / $this->travelTo() |
| ایمیل | net/smtp یا SDK فراهمکننده | Mail::to()->send() | در حافظه / Mail::fake() |
| صف / broker | amqp091-go، franz-go | dispatch()، ShouldQueue | در حافظه / Queue::fake() |
| فایل | AWS SDK v2 S3 | Storage::disk('s3') | پوشهٔ موقت / Storage::fake() |
درمان / طرز استفاده: adapter استرایپ خطای فراهمکننده را به خطای خود port یعنی ErrPaymentDeclined ترجمه میکند. صدازننده هیچوقت adapter را import نمیکند تا رد شدن کارت را تشخیص بدهد. facadeهای لاراول اینجا مشکلی ندارند: adapter تنها لایهای است که اجازه دارد فریمورک را بشناسد.
قاعدهٔ وابستگی، port و adapter، ریشهٔ ترکیب حیاتی
این بلوک دربارهٔ الگوی «port و adapter (Ports and adapters)» است که معماری ششضلعی (Hexagonal architecture) و معماری تمیز (Clean architecture) هر دو بر آن تکیه دارند.
به زبان ساده: داخل (دامنه و use caseها) نیازش را به شکل interface میگوید. بیرون (دیتابیس، HTTP، Stripe) به این interfaceها وصل میشود. یک فایل هنگام شروع برنامه تصمیم میگیرد کدام دوشاخه به کدام پریز برود.
بدفهمی رایج: «hexagonal یعنی هر کلاسی interface بگیرد.» port جایی است که داخل به یک فناوری میرسد: ذخیرهسازی، شبکه، زمان، تصادف. PricingService یک مقدار دامنه است که گونهٔ دیگری ندارد، پس interface لازم ندارد. interfaceی که دقیقاً یک پیادهسازی دارد و مرز فناوری هم نیست فقط یک لایهٔ واسطهٔ اضافه است.
تعریف: قاعدهٔ وابستگی (Martin) میگوید وابستگیهای کد منبع فقط رو به داخلاند و کد داخلی هیچوقت نام نوعی از بیرون را نمیبرد. port interfaceی است که مال لایهٔ داخلی است. Cockburn میان portهای راننده (Driving / primary)، که بیرون از راهشان برنامه را صدا میزند، و portهای راندهشده (Driven / secondary)، که برنامه از راهشان بیرون را صدا میزند، فرق میگذارد. adapter میان یک فناوری و یک port ترجمه میکند. ریشهٔ ترکیب تنها جایی است، معمولاً main یا یک service provider، که adapterهای واقعی را میسازد و تزریق میکند. این همان وارونگی وابستگی (Dependency Inversion) در مقیاس لایههاست. Three Dots Labs دربارهٔ یک تداخل نام هشدار میدهند: "Our ports are Hexagonal Architecture's Primary Adapters. Our adapters are Hexagonal Architecture's Secondary Adapters." این صفحه معنای Cockburn را به کار میبرد: portها interfaceاند (app/ports.go)، و هم HTTP handler و هم کد پستگرس adapter حساب میشوند.
این نقشه ششضلعی Sales را نشان میدهد. در سمت چپ چهار adapter راننده هستند (HTTP همراه با Form Request، job صف، دستور CLI، تست) و همه همان use caseها را صدا میزنند. در سمت راست پنج port راندهشده هست و هر کدام دو adapter قابلتعویض دارد: پستگرس یا حافظه، Stripe یا جعلی، ساعت سیستم یا ساعت ثابت، outbox در SQL یا حافظه، فهرست قیمت محلی یا HTTP. ریشهٔ ترکیب در پایین تصمیم میگیرد کدام وصل شود.
Moment What runs Knows concrete types?
1 start-up main(): open DB, build stripe.Gateway, clock yes: only here
2 start-up main(): PlaceOrderHandler{UoW: pg, Payments: ...} yes: only here
3 start-up main(): wrap with decorator.Logging yes: only here
4 request httpapi.PlaceOrder decodes JSON -> command no: knows the handler interface
5 request handler.Handle(ctx, cmd) no: knows ports
6 request stripe.Gateway.Authorize yes, of its own technology onlyسناریوهای واقعی: در Wild Workouts با نوشتن یک adapter تازه Firestore را با MySQL عوض کردند (hour_mysql_repository.go کنار hour_firestore_repository.go). کل use case در تست روی memory.Store اجرا میشود. در یک بازار Stripe با Adyen عوض میشود. query handler به یک read replica وصل میشود.
سیمکشی کجا زندگی میکند:
| Stack | ریشهٔ ترکیب | سبک DI |
|---|---|---|
| Go | cmd/<app>/main.go یا service.NewApplication() (Wild Workouts) | تزریق دستی از راه constructor؛ در صورت نیاز تولید کد با google/wire |
| Laravel 13 | service provider: ویژگی $bindings، و register() با singleton، bind، extend | سیمکشی خودکار type hintهای constructor توسط container |
| Spring | کلاسهای @Configuration، component scan | container مبتنی بر annotation |
| .NET | Program.cs با builder.Services.AddScoped<IPort, Adapter>() | container داخلی |
درمان / طرز استفاده: قاعده را ماشینی اجرا کنید. ماژول Go تستی دارد که اگر sales یکی از database/sql، net/http، log/slog، os یا هر پکیج app یا adapter را import کند، شکست میخورد. در لاراول همین کار را architecture testing در Pest یا Deptrac میکند. Layered Monolith هر دو را نشان میدهد.
command handler و query handler مهم
به زبان ساده: application serviceها را دو دسته کنید: آنهایی که چیزی را تغییر میدهند و (تقریباً) هیچ برنمیگردانند، و آنهایی که چیزی برمیگردانند و هیچ تغییری نمیدهند.
بدفهمی رایج: «CQS در لایهٔ کاربرد یعنی CQRS با دو دیتابیس و event sourcing.» نه. command handler و query handler جدا میتوانند از همان جدولها بخوانند و در آنها بنویسند. CQRS، یعنی مدلهای خواندنی جدا که با رویداد بهروز میمانند، قدم بعدی و اختیاری است (Event Sourcing & CQRS، Data Patterns in Microservices).
تعریف: جداسازی command و query (Meyer، به روایت Fowler) که روی use caseها اعمال شده. command handler یک command DTO میگیرد، از یک aggregate و یک تراکنش رد میشود، رویداد میسازد و هیچ یا نتیجهای کمینه برمیگرداند (شناسهٔ تازه، مبلغ، پرچم replay). query handler یک query DTO میگیرد، مستقیم از جدول، view، replica یا cache میخواند، aggregate بار نمیکند، تراکنش نوشتنی باز نمیکند و DTOهایی همشکل نیاز صدازننده برمیگرداند. Wild Workouts آنها را به شکل app.Application{Commands: ..., Queries: ...} سیمکشی میکند.
Request Handler Touches Returns
1 POST /orders PlaceOrderHandler Order aggregate, tx, outbox {order_id, total}
2 GET /customers/c-1/orders CustomerOrdersHandler SELECT ... LIMIT 20 [OrderSummary]
3 POST /orders/o-1/cancel CancelOrderHandler Order aggregate, tx, outbox 204
4 GET /orders/o-1 OrderDetailsHandler view / replica OrderDetailsسناریوهای واقعی: صفحهٔ «سفارشهای من» از یک view غیرنرمال order_summaries روی replica میخواند، در حالی که PlaceOrder روی primary مینویسد. داشبورد ادمین از cacheی میخواند که با رویدادهای OrderPlaced بازسازی میشود. یک job خروجیگیری query handler را با cursor صدا میزند (Cursors & Streaming).
| داده برمیگرداند | state را تغییر میدهد | انبارهٔ معمول | cache پذیر است؟ | |
|---|---|---|---|---|
| Command handler | کمینه (id، مبلغ) | بله | دیتابیس اصلی | نه |
| Query handler | بله | نه | replica، view، cache، search index | بله |
| «commandی که کل شیء را برمیگرداند» | بله | بله | اصلی | cache کردنش سخت است؛ مصالحهای رایج |
درمان / طرز استفاده: app/query در Go و Queries/CustomerOrdersHandler در Laravel. دقت کنید که query handler نه repository دارد و نه شیء دامنه.
تراکنش و unit of work حیاتی
به زبان ساده: application service تصمیم میگیرد تراکنش دیتابیس کجا شروع شود و کجا تمام. دامنه اصلاً نمیداند تراکنش وجود دارد. یک use case معمولاً یعنی یک تراکنش که یک aggregate را تغییر میدهد.
بدفهمی رایج: «کل handler را در تراکنش بپیچید، امنتر است.» نه اگر handler، Stripe را صدا بزند. فراخوانی شبکه داخل تراکنش یک اتصال دیتابیس و قفل سطرها را تا هر وقت فراهمکننده طول بدهد نگه میدارد. بعد ممکن است فراخوانی موفق شود و commit شکست بخورد، و شما کارتی را برای سفارشی شارژ کردهاید که وجود ندارد. فراخوانیهای بیرونی را بیرون از تراکنش نگه دارید و جبرانشان کنید.
تعریف: unit of work (Fowler، PoEAA) تغییرهای یک تراکنش کسبوکاری را دنبال میکند و همه را اتمی commit میکند. در این فصل یک port است: UnitOfWork.Do(ctx, fn) در Go و UnitOfWork::run(callable) در Laravel. به fn repositoryها و outboxی میدهد که به یک تراکنش دیتابیس بستهاند. اگر fn عادی برگردد commit میشود و در غیر این صورت rollback. قاعدهٔ Aggregates هنوز برقرار است: یک aggregate در هر تراکنش، و aggregateهای دیگر با رویداد و بهتدریج بهروز میشوند. سطح جداسازی همان پیشفرض دیتابیس است، مگر use case بیشتر بخواهد (Isolation Levels).
T Application service Database Stripe
1 t0 Get(o-1): not found SELECT ... (no tx)
2 t1 Authorize(order-o-1, 66.50) PaymentIntent pi_1 (requires_capture)
3 t2 order.Place(...) (nothing yet)
4 t3 uow.Do: BEGIN BEGIN
5 t4 INSERT sales_orders, sales_order_lines rows locked by this tx
6 t5 INSERT outbox (sales.order.placed.v1)
7 t6 COMMIT COMMIT: order and event durable together
8 t6' if COMMIT fails: Void(pi_1) pi_1 canceledسناریوهای واقعی: timeout سیثانیهای درگاه پرداخت داخل تراکنش، pool اتصال را خالی میکند (Connection Pooling). بنبست میان دو use case که دو aggregate را با ترتیب متفاوت لمس میکنند (Deadlocks). listener لاراولی که روی اتصال دوم بیرون از تراکنش مینویسد و هیچوقت rollback نمیشود.
| Stack | API تراکنش | تلاش مجدد در بنبست / شکست serialization |
|---|---|---|
Go database/sql | db.BeginTx(ctx, opts)، tx.Commit()، tx.Rollback() | حلقهٔ خودتان روی SQLSTATE 40001 / 40P01 |
| pgx | pgx.BeginFunc(ctx, db, fn) | حلقهٔ خودتان |
| Laravel 13 | DB::transaction(fn, attempts)، ConnectionInterface::transaction | آرگومان دوم closure را هنگام بنبست دوباره اجرا میکند |
| Spring | @Transactional روی application service | @Retryable |
درمان / طرز استفاده: postgres.UnitOfWork در Go و DatabaseUnitOfWork در Laravel. هر دو adapterی پشت port هستند، پس use case هیچوقت database/sql یا facade DB را import نمیکند.
رویداد دامنه از دل use case مهم
به زبان ساده: aggregate وقتی تغییر میکند یادداشت میکند «OrderPlaced». application service این یادداشتها را برمیدارد و همراه سفارش ذخیره میکند. چیز دیگری آنها را بعد از اینکه ذخیره واقعاً انجام شد میرساند.
بدفهمی رایج: «رویداد را درست بعد از order.Place() پخش کن.» اگر تراکنش بعداً rollback شود، Fulfilment شروع کرده به جمع کردن اقلام سفارشی که وجود ندارد. رویدادها فقط بعد از commit از پردازه بیرون میروند.
تعریف: aggregate رویدادهای دامنه (Domain event) را در حافظه ثبت میکند (PullEvents()/pullEvents()). application service آنها را جمع میکند و در همان تراکنش aggregate مینویسد. یا در جدول outbox که یک relay بعد از commit منتشرش میکند (Outbox Pattern)، یا به یک dispatcher درونپردازهای که تا commit نگهشان میدارد. Laravel 13 گزینهٔ دوم را دارد: رویدادی که ShouldDispatchAfterCommit را پیاده کند فقط بعد از commit تراکنش باز پخش میشود ("If the transaction fails, the event will be discarded")، و یک job را میشود با ->afterCommit() dispatch کرد. تفاوت رویداد دامنه با رویداد یکپارچهسازی و payloadهایشان در Domain Events vs Integration Events آمده.
Option Same tx as order? Survives crash after commit? Leaves the process?
1 dispatch before commit no n/a: may announce a rollback yes: wrong
2 ShouldDispatchAfterCommit held until commit no: lost if process dies in-process listeners
3 job ->afterCommit() pushed after commit no: lost if process dies yes, via queue
4 outbox row + relay yes yes yes: at-least-onceسناریوهای واقعی: OrderPlaced ← Fulfilment موجودی رزرو میکند و Billing هنگام ارسال برداشت میکند (Saga Pattern). OrderPlaced ← ایمیل رسید فرستاده میشود (listener درونپردازهای کافی است؛ برای بعضی کسبوکارها از دست رفتن یک ایمیل در crash قابل قبول است). OrderPlaced ← projection «سفارشهای من» بهروز میشود. سبکهای رویدادمحور فراتر از یک use case در Event-Driven Architecture آمدهاند.
درمان / طرز استفاده: هر دو پیادهسازی order.PullEvents() را داخل uow.Do به port Outbox اضافه میکنند. مصرفکنندهها هنوز باید idempotent باشند، چون relay دستکم یک بار تحویل میدهد (Idempotent Consumers & Inbox).
دغدغههای سراسری به شکل decorator مهم
به زبان ساده: لاگ، متریک، tracing، بررسی مجوز، تلاش مجدد و idempotency دور use case پیچیده میشوند، مثل لایههای پیاز، نه اینکه داخلش نوشته شوند.
بدفهمی رایج: «decorator جای مجوز در دامنه را میگیرد.» دو چیز متفاوت هر دو مجوز نامیده میشوند. آیا این کاربر اصلاً اجازه دارد این use case را صدا بزند؟ مال لبه است (authorize() در Form Request، decorator، middleware). آیا این سفارش بعد از ارسال قابل لغو است؟ قاعدهٔ دامنه است و در aggregate میماند.
تعریف: decorator (Structural Patterns) همان interface handler را پیاده میکند، کار خودش را انجام میدهد و بعد به handler پیچیدهشده واگذار میکند. Wild Workouts روی هر handler decorator.ApplyCommandDecorators (لاگ بهعلاوهٔ متریک) را اعمال میکند. container لاراول همین را با extend میدهد: "you may run additional code to decorate or configure the service." middleware در HTTP همین ایده است، یک لایه بیرونیتر. Context لاراول یک correlation id اضافه میکند که "is automatically appended as metadata to any log entries" و همراه jobهای صف هم میرود.
Call chain for POST /orders
1 AssignCorrelationId middleware Context::add('correlation_id', ...)
2 PlaceOrderRequest authorize(): can('place-orders'); rules(): shape
3 LogsPlaceOrder (decorator) start timer
4 PlaceOrderHandler the use case
5 LogsPlaceOrder (decorator) log ok/failed + duration (with correlation_id)
6 Controller map result / exception to HTTP status| دغدغه | کجا میرود | Go | Laravel 13 |
|---|---|---|---|
| لاگ و زمانسنجی | Decorator | decorator.Logging با log/slog | LogsPlaceOrder از راه $this->app->extend() |
| متریک | Decorator | decorator.Measured روی port Metrics | decoratorی که client متریک را صدا میزند |
| Correlation id | middleware لبه | مقدار در context.Context | Context::add() در middleware |
| مجوز اجرای use case | لبه یا decorator | decorator.Authorized | authorize() در Form Request، Gate، policy |
| Idempotency | کلید طبیعی داخل use case، یا decorator | OrderID بهعنوان کلید؛ decorator.Idempotent برای commandهای بیکلید | هدر Idempotency-Key بهعنوان شناسهٔ سفارش؛ گونهٔ middleware |
| تلاش مجدد در تعارض | decorator دور use case | حلقهٔ app.Retry روی ErrConcurrencyConflict، مثل Aggregates (در این ماژول نیست) | DB::transaction($fn, 3) برای بنبست |
درمان / طرز استفاده: decoratorهای Go و provider لاراول.
DTO و اعتبارسنجی در لبه مهم
به زبان ساده: use case یک شیء ورودی کوچک و ساده میگیرد و یک شیء خروجی کوچک و ساده برمیگرداند. بررسی اینکه JSON شکل درستی دارد پیش از use case انجام میشود. بررسی قاعدههای کسبوکار داخل دامنه انجام میشود.
بدفهمی رایج: «اعتبارسنجی یکجا زندگی میکند.» دو نوع است. اعتبارسنجی شکل (الزامی، عدد صحیح، آرایه، طول بیشینه) مال لبه است: Form Request یا decoder در adapter HTTP. اعتبارسنجی قاعده (حداکثر ۵۰ عدد در هر سطر، سفارش باید پیشنویس باشد) مال دامنه است، چون برای job صف و CLI هم باید برقرار باشد. تکرار یک قاعده در لبه برای پیام خطای بهتر اشکالی ندارد، به شرطی که دامنه هنوز اجرایش کند.
تعریف: input DTO (همان command) شیء دادهٔ تغییرناپذیری است با فیلدهای ساده یا value object و بیرفتار: PlaceOrder{OrderID, CustomerID, Items, PaymentToken}. output DTO چیزی است که صدازننده لازم دارد: PlaceOrderResult{OrderID, Total, Replay}. هیچکدام خود aggregate نیستند. برگرداندن aggregate جزئیات دامنه را به controller نشت میدهد و دعوتش میکند متدهایش را صدا بزند. مستندات لاراول Form Requestها را "custom request classes that encapsulate their own validation and authorization logic" توصیف میکند. اینجا کار Form Request با toCommand() تمام میشود.
Layer Sees Rejects with
1 HTTP adapter JSON body, headers 422 shape error, 428 no Idempotency-Key
2 Form Request validated array 403 (authorize), 422 (rules)
3 Use case PlaceOrder DTO nothing of its own
4 Domain OrderLine(quantity=99) OrderRuleViolated -> 422
5 Adapter Stripe 402 card_error PaymentDeclined -> 402سناریوهای واقعی: همان DTO PlaceOrder از HTTP، از یک job ورود CSV و از دستور CLI artisan orders:place ساخته میشود. یک resolver در GraphQL به همان command نگاشت میشود. نسخهٔ دوم API که JSON را عوض میکند ولی command را نه.
درمان / طرز استفاده: PlaceOrderRequest::toCommand() در Laravel، httpapi.PlaceOrder در Go.
نامگذاری: پسوند «Service» تکمیلی
به زبان ساده: نام کلاسی که به Service، Manager، Helper یا Processor ختم میشود چیزی دربارهٔ کارش نمیگوید. آن را به نام عملیات یا مفهوم بنامید، همانطور که کسبوکار میگوید.
بدفهمی رایج: «DDD این پسوند را لازم دارد تا بدانیم سرویس است.» Evans میخواهد نام سرویس بخشی از زبان فراگیر باشد. PricingService این آزمون را پاس میکند، چون کسبوکار از «قیمتگذاری» حرف میزند. OrderService پاس نمیکند، چون سطلی است برای هر چیزی که به سفارش دست میزند.
تعریف: یک قرارداد نامگذاری است، نه یک الگو. use caseها فعلاند (PlaceOrder، CancelOrder). domain serviceها اسم یا فعل دامنهاند (PricingService، Overbooking، FundsTransfer). adapterهای زیرساخت به نام فناوریشان نامیده میشوند (StripePaymentGateway، SmtpMailer). portها به نام توانایی (PaymentGateway، Clock). توصیهٔ نامگذاری پکیج در Go هم همین جهت را هل میدهد: pricing.Quote بهتر از services.PricingService.Quote خوانده میشود.
Name in the codebase What it really is Better name
1 OrderService god class PlaceOrder, CancelOrder, PricingService
2 PaymentService Stripe client StripePaymentGateway (behind PaymentGateway)
3 OrderManager repository + rules OrderRepository + methods on Order
4 TimeService clock Clock
5 OrderHelper::total() pricing rule PricingService.Quote or Order.Totalدرمان / طرز استفاده: هنگام بازآرایی در حل مسئلههای کلاسیک نام را عوض کنید.
سازوکار (Mechanics)
چرخهٔ درخواست قدم به قدم حیاتی
نمودار توالی یک POST /orders را روی شش خط زندگی دنبال میکند. adapter HTTP، DTO PlaceOrder را میفرستد (۱). handler بررسی idempotency را انجام میدهد (۲)، قیمت و سطح مشتری و تخفیفها را از portها میخواند (۳)، سفارش را میسازد و از PricingService قیمت میگیرد (۴)، و بیرون از هر تراکنشی مجوز پرداخت میگیرد (۵). Place رویداد OrderPlaced را ثبت میکند (۶) و سفارش و رویدادهایش در یک تراکنش ذخیره میشوند (۷). relay بعد از commit منتشر میکند (۸) و adapter HTTP با ۲۰۱ جواب میدهد (۹).
- لبه. middleware شناسهٔ correlation را میگذارد. adapter یا Form Request شکل ورودی و حق صدازننده برای اجرای use case را بررسی میکند و command DTO را میسازد.
- Decoratorها. لاگ، متریک و در صورت استفاده decorator idempotency دور handler پیچیده میشوند.
- خواندن idempotency. کلید طبیعی command (
OrderIDکه از هدرIdempotency-Keyآمده) جستوجو میشود. اگر پیدا شود، نتیجهٔ ذخیرهشده باReplay=trueبرمیگردد. - ورودیها. قیمت، سطح و تخفیف از portها میآیند. در یک modular monolith اینها read modelهای محلیاند که رویدادهای Catalog و Identity پرشان میکنند، هرگز جدولهای آن ماژولها.
- دامنه.
NewOrderناورداییهای سطرها را بررسی میکند وPricingService.Quoteقیمت میدهد. هیچچیز این بخش به دلیل فنی شکست نمیخورد. - اثر جانبی بیرونی.
PaymentGateway.Authorizeبا کلید idempotencyorder-<id>. Stripe "the status code and body of the first request made with a given idempotency key" را نگه میدارد و در تلاشهای بعدی همان را برمیگرداند. - تغییر state.
order.Place(quote, ref, now)رویدادOrderPlacedرا ثبت میکند. - تراکنش. سفارش، سطرهایش و سطرهای outbox را درج و commit کنید. اگر کلید اصلی نقض شد (درخواست تکراری همزمان)، نتیجهٔ برنده را برگردانید و void نکنید، چون هر دو درخواست یک مجوز مشترک دارند. در هر شکست دیگری مجوز را void کنید.
- بعد از commit. relay در outbox منتشر میکند و listenerهای درونپردازهای
ShouldDispatchAfterCommitاجرا میشوند.
جدولها و تراکنش در SQL
جدولهای Sales پشت adapterها، و آنچه unit of work برای یک command به PostgreSQL میفرستد:
-- Sales owns these tables; no other module writes to them.
CREATE TABLE sales_orders (
id text PRIMARY KEY, -- client-generated: the idempotency key
customer_id text NOT NULL,
status text NOT NULL,
total_minor bigint,
currency char(3),
payment_ref text,
placed_at timestamptz
);
CREATE TABLE sales_order_lines (
order_id text NOT NULL REFERENCES sales_orders(id) ON DELETE CASCADE,
position smallint NOT NULL,
sku text NOT NULL,
quantity smallint NOT NULL CHECK (quantity BETWEEN 1 AND 50), -- defence in depth
unit_minor bigint NOT NULL,
PRIMARY KEY (order_id, position)
);
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
event_name text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
-- One PlaceOrder command = one transaction (READ COMMITTED, the PostgreSQL default).
BEGIN;
INSERT INTO sales_orders (id, customer_id, status, total_minor, currency, payment_ref, placed_at)
VALUES ('o-1001', 'c-gold', 'placed', 6650, 'EUR', 'pi_3Q...', now());
INSERT INTO sales_order_lines VALUES ('o-1001', 0, 'MUG', 5, 1200), ('o-1001', 1, 'TEA', 2, 800);
INSERT INTO outbox (event_name, payload)
VALUES ('sales.order.placed.v1', '{"order_id":"o-1001","total_minor":6650,"currency":"EUR"}');
COMMIT;
-- A concurrent duplicate fails on the first INSERT:
-- ERROR: duplicate key value violates unique constraint "sales_orders_pkey" (SQLSTATE 23505)قید CHECK یک قاعدهٔ دامنه را بهعنوان تور ایمنی تکرار میکند. خانهٔ قاعده هنوز OrderLine است. نسخهٔ دیتابیس فقط کدی را میگیرد که دامنه را دور زده.
خطاهایی که میبینید و لایهای که ترجمهشان میکند
| خطا | چه کسی میسازد | چه کسی ترجمه میکند | به چه | HTTP |
|---|---|---|---|---|
quantity must be between 1 and 50 | دامنه (ErrBadQuantity، OrderRuleViolated) | adapter راننده | پیام برای کاربر | 422 |
SQLSTATE 23505 unique_violation (PostgreSQL)، خطای 1062 ER_DUP_ENTRY (MySQL) | دیتابیس | adapter مخزن | ErrDuplicateOrder / DuplicateOrder | 200 replay |
Illuminate\Database\UniqueConstraintViolationException | query builder لاراول | EloquentOrderRepository | DuplicateOrder | 200 replay |
SQLSTATE 40001 serialization_failure، 40P01 deadlock_detected؛ MySQL 1213 | دیتابیس | decorator تلاش مجدد / DB::transaction($fn, 3) (توصیهشده؛ در این نمونه نیست، چون closure باید رویدادها را دوباره بگیرد) | تلاش مجدد، بعد 503 | 503 |
Stripe 402 با error.type = card_error و code = card_declined | Stripe | stripe.Gateway / StripePaymentGateway | ErrPaymentDeclined / PaymentDeclined | 402 |
Stripe 409 "conflicts with another request (perhaps due to using the same idempotent key)" | Stripe | adapter | تلاش مجدد پس از مکثی کوتاه (توصیهشده؛ نمونه آن را بهصورت خطا بالا میدهد) | 409 / retry |
AuthorizationException (وقتی authorize() در Form Request مقدار false برگرداند) | Laravel | فریمورک | 403 | 403 |
ValidationException | قواعد Form Request | فریمورک | 422 همراه خطای فیلدها | 422 |
context deadline exceeded | context در Go | httpapi (errors.Is(err, context.DeadlineExceeded)) | timeout | 504 |
قاعدهٔ پشت جدول: هر خطا در همان مرزی که از آن رد میشود ترجمه میشود. دامنه هیچوقت 23505 را نمیبیند و controller هیچوقت card_error را.
Go
ماژول academy/domain-application-infrastructure-services شکل Wild Workouts را دنبال میکند: sales (دامنه)، app (portها)، app/command و app/query (use caseها)، app/decorator، adapters/*، cmd/shop (ریشهٔ ترکیب). gofmt -l . و go vet ./... تمیزند و go test ./... پاس میشود.
دامنه: aggregate، port و domain service
// Package sales is the domain layer of the Sales bounded context. It imports
// nothing from the application or infrastructure layers: no SQL, no HTTP, no
// clock, no logger. Everything it needs from the outside is passed in.
package sales
import (
"errors"
"time"
)
type (
// OrderID is the identity of the Order aggregate. The client may supply it,
// which makes PlaceOrder naturally idempotent.
OrderID string
// CustomerID references a customer in the Identity context by id.
CustomerID string
// SKU references a Catalog product by id.
SKU string
)
// Status is the Order lifecycle.
type Status string
// Order states used in this chapter.
const (
Draft Status = "draft"
Placed Status = "placed"
)
// Domain errors, phrased in the ubiquitous language.
var (
ErrEmptyOrder = errors.New("an order needs at least one line")
ErrBadQuantity = errors.New("quantity must be between 1 and 50")
ErrAlreadyPlaced = errors.New("the order has already been placed")
ErrQuoteMismatch = errors.New("the quote was made for another order")
ErrOrderNotFound = errors.New("order not found")
ErrDuplicateOrder = errors.New("an order with this id already exists")
)
// Line is one order line: a SKU, a quantity and the catalogue unit price.
type Line struct {
SKU SKU
Quantity int
UnitPrice Money
}
// Order is the aggregate root.
type Order struct {
id OrderID
customer CustomerID
lines []Line
status Status
total Money
payment string
placedAt time.Time
events []Event
}
// NewOrder creates a draft order and checks the line invariants.
func NewOrder(id OrderID, customer CustomerID, lines []Line) (*Order, error) {
if len(lines) == 0 {
return nil, ErrEmptyOrder
}
for _, l := range lines {
if l.Quantity < 1 || l.Quantity > 50 {
return nil, ErrBadQuantity
}
}
cp := append([]Line(nil), lines...)
return &Order{id: id, customer: customer, lines: cp, status: Draft}, nil
}
// Place freezes the priced total, stores the payment reference and records
// OrderPlaced. The time is an argument: the domain never reads a clock.
func (o *Order) Place(q Quote, paymentRef string, now time.Time) error {
if o.status != Draft {
return ErrAlreadyPlaced
}
if q.OrderID != o.id {
return ErrQuoteMismatch
}
o.status, o.total, o.payment, o.placedAt = Placed, q.Total, paymentRef, now
o.events = append(o.events, OrderPlaced{
OrderID: o.id, CustomerID: o.customer, Total: q.Total, PaymentRef: paymentRef, PlacedAt: now,
})
return nil
}
// PullEvents returns the recorded events and clears them, so a retry of the
// same in-memory object cannot publish them twice.
func (o *Order) PullEvents() []Event {
ev := o.events
o.events = nil
return ev
}
// Read-only accessors.
func (o *Order) ID() OrderID { return o.id }
func (o *Order) Customer() CustomerID { return o.customer }
func (o *Order) Lines() []Line { return append([]Line(nil), o.lines...) }
func (o *Order) Status() Status { return o.status }
func (o *Order) Total() Money { return o.total }
func (o *Order) PaymentRef() string { return o.payment }
func (o *Order) PlacedAt() time.Time { return o.placedAt }
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }
// Rehydrate rebuilds an Order from storage. Only repositories call it.
func Rehydrate(id OrderID, customer CustomerID, lines []Line, status Status, total Money, payment string, placedAt time.Time) *Order {
return &Order{id: id, customer: customer, lines: lines, status: status, total: total, payment: payment, placedAt: placedAt}
}package sales
import "context"
// OrderRepository is a port DEFINED BY THE DOMAIN and implemented in
// adapters/postgres and adapters/memory. The domain owns the interface;
// infrastructure owns the SQL.
type OrderRepository interface {
Get(ctx context.Context, id OrderID) (*Order, error)
Add(ctx context.Context, o *Order) error
}package sales
import "fmt"
// Tier is the loyalty tier of a customer, as Sales understands it.
type Tier string
// Tiers known to the pricing policy.
const (
TierStandard Tier = "standard"
TierGold Tier = "gold"
)
// Promotion is a value object: "buy MinQty of SKU, get PercentOff on that line".
type Promotion struct {
Code string
SKU SKU
MinQty int
PercentOff int
}
// Quote is the result of pricing: a value object, not an entity.
type Quote struct {
OrderID OrderID
Subtotal Money
Discount Money
Shipping Money
Total Money
}
// PricingService is a DOMAIN service. Pricing is a significant domain
// operation that belongs to no single entity: it combines the order lines,
// the customer's tier and the active promotions. It is stateless, has no I/O
// and speaks only the ubiquitous language, so it is a plain struct with a
// pure method. Policy numbers are fields, set once at wiring time.
type PricingService struct {
GoldPercentOff int // e.g. 5
FreeShippingFrom int64 // minor units, e.g. 5000 = 50.00
FlatShippingMinor int64 // e.g. 495 = 4.95
}
// Quote prices an order. Rules, in order:
// 1. subtotal = sum(unit price x quantity)
// 2. a line promotion applies when quantity >= MinQty (best one per line)
// 3. gold customers get GoldPercentOff on the subtotal after promotions
// 4. shipping is free from FreeShippingFrom, else a flat fee
func (p PricingService) Quote(o *Order, tier Tier, promos []Promotion) (Quote, error) {
cur := o.lines[0].UnitPrice.Currency
sub, disc := Money{Currency: cur}, Money{Currency: cur}
for _, l := range o.lines {
lineTotal := l.UnitPrice.Times(l.Quantity)
var err error
if sub, err = sub.Add(lineTotal); err != nil {
return Quote{}, fmt.Errorf("pricing %s: %w", l.SKU, err)
}
best := 0
for _, pr := range promos {
if pr.SKU == l.SKU && l.Quantity >= pr.MinQty && pr.PercentOff > best {
best = pr.PercentOff
}
}
disc, _ = disc.Add(lineTotal.PercentOff(best))
}
afterPromos := sub.Sub(disc)
if tier == TierGold {
loyalty := afterPromos.PercentOff(p.GoldPercentOff)
disc, _ = disc.Add(loyalty)
}
net := sub.Sub(disc)
ship := Money{Minor: p.FlatShippingMinor, Currency: cur}
if net.Minor >= p.FreeShippingFrom {
ship = Money{Currency: cur}
}
total, _ := net.Add(ship)
return Quote{OrderID: o.id, Subtotal: sub, Discount: disc, Shipping: ship, Total: total}, nil
}کاربرد: portها، command handler، query handler، decoratorها
// Package app holds the ports the application layer needs from the outside
// world. They are interfaces owned by the inside and implemented by adapters
// (Cockburn's ports and adapters; DIP at the architectural level).
package app
import (
"context"
"errors"
"time"
"academy/domain-application-infrastructure-services/sales"
)
// Clock is an infrastructure-service port: "what time is it?"
type Clock interface{ Now() time.Time }
// ErrPaymentDeclined is the port's own error. Adapters wrap their provider's
// error into it, so callers never import an adapter to recognise a decline.
var ErrPaymentDeclined = errors.New("payment declined")
// PaymentGateway is an infrastructure-service port. The use case speaks in
// its own terms (authorize, void); the Stripe adapter translates.
type PaymentGateway interface {
// Authorize reserves the amount. idempotencyKey makes a retried call safe.
Authorize(ctx context.Context, idempotencyKey string, amount sales.Money, paymentToken string) (ref string, err error)
// Void releases an authorization that will never be captured.
Void(ctx context.Context, ref string) error
}
// Catalog is an anticorruption port to the Catalog context: current unit prices.
type Catalog interface {
UnitPrices(ctx context.Context, skus []sales.SKU) (map[sales.SKU]sales.Money, error)
}
// Customers answers Sales' only question about a customer: the pricing tier.
type Customers interface {
Tier(ctx context.Context, id sales.CustomerID) (sales.Tier, error)
}
// Promotions returns the promotions active at a moment.
type Promotions interface {
Active(ctx context.Context, at time.Time) ([]sales.Promotion, error)
}
// Outbox stores events in the same transaction as the aggregate; a relay
// publishes them after commit (see the Outbox Pattern chapter).
type Outbox interface {
Append(ctx context.Context, events ...sales.Event) error
}
// Tx is what a unit of work hands to the use case: repositories and the
// outbox, all bound to ONE database transaction.
type Tx interface {
Orders() sales.OrderRepository
Outbox() Outbox
}
// UnitOfWork runs fn in one transaction: commit if fn returns nil, else rollback.
type UnitOfWork interface {
Do(ctx context.Context, fn func(ctx context.Context, tx Tx) error) error
}// Package command holds the write-side application services (use cases).
package command
import (
"context"
"errors"
"fmt"
"academy/domain-application-infrastructure-services/app"
"academy/domain-application-infrastructure-services/sales"
)
// PlaceOrder is the input DTO (the command). Plain data, already validated
// for shape at the edge (HTTP adapter); business rules are checked inside.
type PlaceOrder struct {
OrderID sales.OrderID // client-generated: doubles as the idempotency key
CustomerID sales.CustomerID
Items []Item
PaymentToken string
}
// Item is one requested line, without a price: prices come from Catalog.
type Item struct {
SKU sales.SKU
Quantity int
}
// PlaceOrderResult is the output DTO.
type PlaceOrderResult struct {
OrderID sales.OrderID
Total sales.Money
Replay bool // true when the same command was already handled
}
// PlaceOrderHandler is an APPLICATION service: it orchestrates and decides
// nothing about prices, discounts or order rules itself.
type PlaceOrderHandler struct {
UoW app.UnitOfWork
Orders sales.OrderRepository // for the idempotency read outside the tx
Catalog app.Catalog
Customers app.Customers
Promotions app.Promotions
Payments app.PaymentGateway
Clock app.Clock
Pricing sales.PricingService // domain service, a value: no interface needed
}
// Handle runs the use case.
func (h PlaceOrderHandler) Handle(ctx context.Context, cmd PlaceOrder) (PlaceOrderResult, error) {
// 1. Idempotency: the same OrderID twice returns the first result.
if existing, err := h.Orders.Get(ctx, cmd.OrderID); err == nil {
return PlaceOrderResult{OrderID: existing.ID(), Total: existing.Total(), Replay: true}, nil
} else if !errors.Is(err, sales.ErrOrderNotFound) {
return PlaceOrderResult{}, err
}
// 2. Gather the inputs the domain needs (reads through ports).
skus := make([]sales.SKU, 0, len(cmd.Items))
for _, it := range cmd.Items {
skus = append(skus, it.SKU)
}
prices, err := h.Catalog.UnitPrices(ctx, skus)
if err != nil {
return PlaceOrderResult{}, fmt.Errorf("catalog: %w", err)
}
lines := make([]sales.Line, 0, len(cmd.Items))
for _, it := range cmd.Items {
p, ok := prices[it.SKU]
if !ok {
return PlaceOrderResult{}, fmt.Errorf("unknown sku %q", it.SKU)
}
lines = append(lines, sales.Line{SKU: it.SKU, Quantity: it.Quantity, UnitPrice: p})
}
tier, err := h.Customers.Tier(ctx, cmd.CustomerID)
if err != nil {
return PlaceOrderResult{}, fmt.Errorf("customers: %w", err)
}
now := h.Clock.Now()
promos, err := h.Promotions.Active(ctx, now)
if err != nil {
return PlaceOrderResult{}, fmt.Errorf("promotions: %w", err)
}
// 3. Domain: the aggregate checks its invariants, the domain service prices.
order, err := sales.NewOrder(cmd.OrderID, cmd.CustomerID, lines)
if err != nil {
return PlaceOrderResult{}, err
}
quote, err := h.Pricing.Quote(order, tier, promos)
if err != nil {
return PlaceOrderResult{}, err
}
// 4. Infrastructure service, OUTSIDE the database transaction: never hold
// row locks while waiting on a payment provider.
ref, err := h.Payments.Authorize(ctx, "order-"+string(order.ID()), quote.Total, cmd.PaymentToken)
if err != nil {
return PlaceOrderResult{}, fmt.Errorf("payment: %w", err)
}
if err := order.Place(quote, ref, now); err != nil {
_ = h.Payments.Void(ctx, ref)
return PlaceOrderResult{}, err
}
// 5. One transaction: save the aggregate and its events together.
err = h.UoW.Do(ctx, func(ctx context.Context, tx app.Tx) error {
if err := tx.Orders().Add(ctx, order); err != nil {
return err
}
return tx.Outbox().Append(ctx, order.PullEvents()...)
})
if errors.Is(err, sales.ErrDuplicateOrder) {
// A concurrent request with the same OrderID won the race. Both used the
// same idempotency key, so they share ONE authorization: voiding it here
// would cancel the winner's payment. Return the winner's result instead.
winner, gerr := h.Orders.Get(ctx, cmd.OrderID)
if gerr != nil {
return PlaceOrderResult{}, gerr
}
return PlaceOrderResult{OrderID: winner.ID(), Total: winner.Total(), Replay: true}, nil
}
if err != nil {
// Compensate the side effect we cannot roll back with SQL.
_ = h.Payments.Void(ctx, ref)
return PlaceOrderResult{}, err
}
return PlaceOrderResult{OrderID: order.ID(), Total: quote.Total}, nil
}// Package query holds the read-side application services. A query handler
// changes nothing, loads no aggregate and may read a denormalized view.
package query
import (
"context"
"time"
)
// OrderSummary is the output DTO, shaped for the screen, not for the domain.
type OrderSummary struct {
OrderID string
Status string
TotalMinor int64
Currency string
PlacedAt time.Time
Lines int
}
// OrderSummaries is the read-model port (a SQL view, a replica, a cache...).
type OrderSummaries interface {
ForCustomer(ctx context.Context, customerID string, limit int) ([]OrderSummary, error)
}
// CustomerOrders is the query.
type CustomerOrders struct {
CustomerID string
Limit int
}
// CustomerOrdersHandler returns data; it never mutates state (CQS).
type CustomerOrdersHandler struct{ ReadModel OrderSummaries }
// Handle runs the query.
func (h CustomerOrdersHandler) Handle(ctx context.Context, q CustomerOrders) ([]OrderSummary, error) {
if q.Limit <= 0 || q.Limit > 100 {
q.Limit = 20
}
return h.ReadModel.ForCustomer(ctx, q.CustomerID, q.Limit)
}// Package decorator wraps any command handler with cross-cutting concerns
// (logging, metrics, authorization) without touching the use case itself.
package decorator
import (
"context"
"errors"
"log/slog"
"time"
)
// Handler is the shape every command handler shares.
type Handler[C, R any] interface {
Handle(ctx context.Context, cmd C) (R, error)
}
// HandlerFunc adapts a function to Handler.
type HandlerFunc[C, R any] func(ctx context.Context, cmd C) (R, error)
// Handle implements Handler.
func (f HandlerFunc[C, R]) Handle(ctx context.Context, cmd C) (R, error) { return f(ctx, cmd) }
// Logging logs every execution with its duration and outcome.
func Logging[C, R any](name string, log *slog.Logger, next Handler[C, R]) Handler[C, R] {
return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
start := time.Now()
r, err := next.Handle(ctx, cmd)
log.InfoContext(ctx, "command handled", "command", name,
"duration_ms", time.Since(start).Milliseconds(), "ok", err == nil)
return r, err
})
}
// Metrics counts calls and failures through a tiny port (Prometheus, OTel...).
type Metrics interface {
Inc(name string, labels ...string)
}
// Measured records one counter per outcome.
func Measured[C, R any](name string, m Metrics, next Handler[C, R]) Handler[C, R] {
return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
r, err := next.Handle(ctx, cmd)
outcome := "ok"
if err != nil {
outcome = "error"
}
m.Inc("commands_total", "command", name, "outcome", outcome)
return r, err
})
}
// ErrForbidden is returned by Authorized.
var ErrForbidden = errors.New("forbidden")
// Authorized asks a policy before running the use case.
func Authorized[C, R any](allow func(ctx context.Context, cmd C) bool, next Handler[C, R]) Handler[C, R] {
return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
if !allow(ctx, cmd) {
var zero R
return zero, ErrForbidden
}
return next.Handle(ctx, cmd)
})
}
// Results remembers the result of a command by idempotency key (a table with
// a unique key, Redis SET NX, ...). Put returns false if the key already exists.
type Results[R any] interface {
Get(ctx context.Context, key string) (R, bool, error)
Put(ctx context.Context, key string, r R) (bool, error)
}
// Idempotent is the decorator variant of idempotency: useful when the use
// case has no natural key of its own. PlaceOrder does not need it, because
// its OrderID already is the key and the primary key enforces it.
func Idempotent[C, R any](key func(C) string, store Results[R], next Handler[C, R]) Handler[C, R] {
return HandlerFunc[C, R](func(ctx context.Context, cmd C) (R, error) {
k := key(cmd)
if r, ok, err := store.Get(ctx, k); err != nil || ok {
return r, err
}
r, err := next.Handle(ctx, cmd)
if err != nil {
return r, err
}
_, perr := store.Put(ctx, k, r)
return r, perr
})
}زیرساخت: Postgres، Stripe، HTTP
// Package postgres implements the Sales ports with database/sql. It is the
// only package that knows table names, SQL and SQLSTATE codes.
package postgres
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"academy/domain-application-infrastructure-services/app"
"academy/domain-application-infrastructure-services/sales"
)
// querier is satisfied by both *sql.DB and *sql.Tx.
type querier interface {
ExecContext(ctx context.Context, q string, args ...any) (sql.Result, error)
QueryRowContext(ctx context.Context, q string, args ...any) *sql.Row
QueryContext(ctx context.Context, q string, args ...any) (*sql.Rows, error)
}
// UnitOfWork opens one *sql.Tx per use case.
type UnitOfWork struct{ DB *sql.DB }
// Do implements app.UnitOfWork.
func (u UnitOfWork) Do(ctx context.Context, fn func(ctx context.Context, tx app.Tx) error) error {
t, err := u.DB.BeginTx(ctx, nil) // READ COMMITTED, the PostgreSQL default
if err != nil {
return err
}
if err := fn(ctx, txScope{q: t}); err != nil {
_ = t.Rollback()
return err
}
return t.Commit()
}
type txScope struct{ q querier }
func (s txScope) Orders() sales.OrderRepository { return Orders{Q: s.q} }
func (s txScope) Outbox() app.Outbox { return Outbox{Q: s.q} }
// Orders is the OrderRepository adapter.
type Orders struct{ Q querier }
// Get loads the aggregate root and its lines.
func (r Orders) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
var (
customer, status, currency, payment string
total int64
placedAt time.Time
)
err := r.Q.QueryRowContext(ctx,
`SELECT customer_id, status, total_minor, currency, payment_ref, placed_at
FROM sales_orders WHERE id = $1`, id).
Scan(&customer, &status, &total, ¤cy, &payment, &placedAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, sales.ErrOrderNotFound
}
if err != nil {
return nil, err
}
rows, err := r.Q.QueryContext(ctx,
`SELECT sku, quantity, unit_minor FROM sales_order_lines WHERE order_id = $1 ORDER BY position`, id)
if err != nil {
return nil, err
}
defer rows.Close()
var lines []sales.Line
for rows.Next() {
var l sales.Line
var unit int64
if err := rows.Scan(&l.SKU, &l.Quantity, &unit); err != nil {
return nil, err
}
l.UnitPrice = sales.Money{Minor: unit, Currency: currency}
lines = append(lines, l)
}
return sales.Rehydrate(id, sales.CustomerID(customer), lines, sales.Status(status),
sales.Money{Minor: total, Currency: currency}, payment, placedAt), rows.Err()
}
// Add inserts a new aggregate. A primary-key violation (SQLSTATE 23505)
// becomes the domain error ErrDuplicateOrder.
func (r Orders) Add(ctx context.Context, o *sales.Order) error {
_, err := r.Q.ExecContext(ctx,
`INSERT INTO sales_orders (id, customer_id, status, total_minor, currency, payment_ref, placed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
o.ID(), o.Customer(), o.Status(), o.Total().Minor, o.Total().Currency, o.PaymentRef(), o.PlacedAt())
if err != nil {
if strings.Contains(err.Error(), "23505") {
return sales.ErrDuplicateOrder
}
return fmt.Errorf("insert order: %w", err)
}
for i, l := range o.Lines() {
if _, err := r.Q.ExecContext(ctx,
`INSERT INTO sales_order_lines (order_id, position, sku, quantity, unit_minor) VALUES ($1, $2, $3, $4, $5)`,
o.ID(), i, l.SKU, l.Quantity, l.UnitPrice.Minor); err != nil {
return fmt.Errorf("insert line: %w", err)
}
}
return nil
}
// Outbox writes events into the same transaction as the order.
type Outbox struct{ Q querier }
// publishedTypes maps a domain event's class name to the dotted, versioned
// type of the published language; only the outbox row carries the wire name.
var publishedTypes = map[string]string{
"OrderPlaced": "sales.order.placed.v1",
}
// Append implements app.Outbox.
func (b Outbox) Append(ctx context.Context, events ...sales.Event) error {
for _, e := range events {
name, ok := publishedTypes[e.EventName()]
if !ok {
return fmt.Errorf("outbox: no published type for %s", e.EventName())
}
payload, err := json.Marshal(e)
if err != nil {
return err
}
if _, err := b.Q.ExecContext(ctx,
`INSERT INTO outbox (event_name, payload) VALUES ($1, $2)`, name, payload); err != nil {
return fmt.Errorf("outbox: %w", err)
}
}
return nil
}// Package stripe is an infrastructure adapter: it implements app.PaymentGateway
// over Stripe's HTTP API. Stripe vocabulary (PaymentIntent, capture_method,
// Idempotency-Key) stays in this package and never reaches the domain.
package stripe
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"academy/domain-application-infrastructure-services/app"
"academy/domain-application-infrastructure-services/sales"
)
// Gateway talks to Stripe (or to an httptest server in contract tests).
type Gateway struct {
BaseURL string // https://api.stripe.com
APIKey string
HTTP *http.Client
}
type intent struct {
ID string `json:"id"`
Error *struct {
Type string `json:"type"`
Code string `json:"code"`
} `json:"error"`
}
// Authorize creates a PaymentIntent with capture_method=manual: the money is
// reserved now and captured when Fulfilment ships.
func (g Gateway) Authorize(ctx context.Context, key string, amount sales.Money, token string) (string, error) {
form := url.Values{}
form.Set("amount", strconv.FormatInt(amount.Minor, 10))
form.Set("currency", strings.ToLower(amount.Currency))
form.Set("payment_method", token)
form.Set("capture_method", "manual")
form.Set("confirm", "true")
var in intent
if err := g.post(ctx, "/v1/payment_intents", key, form, &in); err != nil {
return "", err
}
return in.ID, nil
}
// Void cancels an uncaptured PaymentIntent.
func (g Gateway) Void(ctx context.Context, ref string) error {
var in intent
return g.post(ctx, "/v1/payment_intents/"+url.PathEscape(ref)+"/cancel", "void-"+ref, url.Values{}, &in)
}
func (g Gateway) post(ctx context.Context, path, idemKey string, form url.Values, out *intent) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.BaseURL+path, strings.NewReader(form.Encode()))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+g.APIKey)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Idempotency-Key", idemKey) // a retry returns the first result
resp, err := g.HTTP.Do(req)
if err != nil {
return fmt.Errorf("stripe: %w", err)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("stripe: decode: %w", err)
}
if resp.StatusCode == http.StatusPaymentRequired || (out.Error != nil && out.Error.Type == "card_error") {
code := ""
if out.Error != nil {
code = out.Error.Code
}
return fmt.Errorf("stripe %s: %w", code, app.ErrPaymentDeclined)
}
if resp.StatusCode >= 300 {
return fmt.Errorf("stripe: status %d", resp.StatusCode)
}
return nil
}// Package httpapi is a driving (primary) adapter: it turns HTTP into a
// command DTO, calls the application service and maps errors to status codes.
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"academy/domain-application-infrastructure-services/app"
"academy/domain-application-infrastructure-services/app/command"
"academy/domain-application-infrastructure-services/app/decorator"
"academy/domain-application-infrastructure-services/sales"
)
// PlaceOrderHandler is the only thing this adapter needs from the inside.
type PlaceOrderHandler interface {
Handle(ctx context.Context, cmd command.PlaceOrder) (command.PlaceOrderResult, error)
}
type placeOrderBody struct {
CustomerID string `json:"customer_id"`
PaymentToken string `json:"payment_token"`
Items []struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
} `json:"items"`
}
// PlaceOrder serves POST /orders. Shape validation happens here; business
// rules are checked by the domain and come back as domain errors.
func PlaceOrder(h PlaceOrderHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" {
http.Error(w, "Idempotency-Key header required", http.StatusPreconditionRequired) // 428
return
}
var b placeOrderBody
if err := json.NewDecoder(r.Body).Decode(&b); err != nil || b.CustomerID == "" || len(b.Items) == 0 {
http.Error(w, "invalid request", http.StatusUnprocessableEntity)
return
}
cmd := command.PlaceOrder{OrderID: sales.OrderID(key), CustomerID: sales.CustomerID(b.CustomerID), PaymentToken: b.PaymentToken}
for _, it := range b.Items {
cmd.Items = append(cmd.Items, command.Item{SKU: sales.SKU(it.SKU), Quantity: it.Quantity})
}
res, err := h.Handle(r.Context(), cmd)
switch {
case errors.Is(err, sales.ErrBadQuantity), errors.Is(err, sales.ErrEmptyOrder):
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
case errors.Is(err, app.ErrPaymentDeclined):
http.Error(w, err.Error(), http.StatusPaymentRequired)
case errors.Is(err, context.DeadlineExceeded):
http.Error(w, "timeout", http.StatusGatewayTimeout)
case errors.Is(err, decorator.ErrForbidden):
http.Error(w, err.Error(), http.StatusForbidden)
case err != nil:
http.Error(w, "internal error", http.StatusInternalServerError)
default:
status := http.StatusCreated
if res.Replay {
status = http.StatusOK
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{"order_id": res.OrderID, "total": res.Total.String()})
}
}
}ریشهٔ ترکیب
// Command shop is the composition root: the ONE place that knows every
// concrete type and wires adapters into ports. Nothing else calls "new" on
// infrastructure.
package main
import (
"database/sql"
"log"
"log/slog"
"net/http"
"os"
"time"
"academy/domain-application-infrastructure-services/adapters/clock"
"academy/domain-application-infrastructure-services/adapters/httpapi"
"academy/domain-application-infrastructure-services/adapters/memory"
"academy/domain-application-infrastructure-services/adapters/postgres"
"academy/domain-application-infrastructure-services/adapters/stripe"
"academy/domain-application-infrastructure-services/app"
"academy/domain-application-infrastructure-services/app/command"
"academy/domain-application-infrastructure-services/app/decorator"
"academy/domain-application-infrastructure-services/sales"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Driven adapters. With DATABASE_URL unset the in-memory store is used,
// so the binary runs without Docker (a database/sql driver such as pgx's
// stdlib package must be blank-imported for the Postgres branch).
var (
uow app.UnitOfWork
orders sales.OrderRepository
)
if dsn := os.Getenv("DATABASE_URL"); dsn != "" {
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
uow, orders = postgres.UnitOfWork{DB: db}, postgres.Orders{Q: db}
} else {
mem := memory.NewStore()
uow, orders = mem, mem
}
var payments app.PaymentGateway = memory.NewPayments()
if key := os.Getenv("STRIPE_KEY"); key != "" {
payments = stripe.Gateway{BaseURL: "https://api.stripe.com", APIKey: key, HTTP: &http.Client{Timeout: 10 * time.Second}}
}
// Application service with its domain service and ports.
place := command.PlaceOrderHandler{
UoW: uow,
Orders: orders,
Catalog: memory.Catalog{"MUG": sales.EUR(1200), "TEA": sales.EUR(800)},
Customers: memory.Customers{"c-gold": sales.TierGold},
Promotions: memory.Promotions{{Code: "MUG3", SKU: "MUG", MinQty: 3, PercentOff: 10}},
Payments: payments,
Clock: clock.System{},
Pricing: sales.PricingService{GoldPercentOff: 5, FreeShippingFrom: 5000, FlatShippingMinor: 495},
}
// Cross-cutting concerns as decorators, outermost first in reading order.
var h decorator.Handler[command.PlaceOrder, command.PlaceOrderResult] = place
h = decorator.Logging("PlaceOrder", logger, h)
// Driving adapter.
mux := http.NewServeMux()
mux.Handle("POST /orders", httpapi.PlaceOrder(h))
addr := ":8080"
if a := os.Getenv("ADDR"); a != "" {
addr = a
}
logger.Info("listening", "addr", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}تستها: برای هر نوع سرویس یک سبک
domain service یک تست جدولی خالص میگیرد، بدون هیچ fake:
package sales_test
import (
"testing"
"academy/domain-application-infrastructure-services/sales"
)
// A domain service is pure: no fakes, no database, no clock. Table tests only.
func TestPricingService_Quote(t *testing.T) {
policy := sales.PricingService{GoldPercentOff: 5, FreeShippingFrom: 5000, FlatShippingMinor: 495}
promo := sales.Promotion{Code: "MUG3", SKU: "MUG", MinQty: 3, PercentOff: 10}
cases := []struct {
name string
lines []sales.Line
tier sales.Tier
wantTotal int64
wantShip int64
}{
{"small standard order pays shipping", []sales.Line{{SKU: "MUG", Quantity: 1, UnitPrice: sales.EUR(1200)}}, sales.TierStandard, 1695, 495},
{"promotion applies from 3 mugs", []sales.Line{{SKU: "MUG", Quantity: 3, UnitPrice: sales.EUR(1200)}}, sales.TierStandard, 3240 + 495, 495},
{"gold on top of promotion, free shipping", []sales.Line{
{SKU: "MUG", Quantity: 5, UnitPrice: sales.EUR(1200)},
{SKU: "TEA", Quantity: 2, UnitPrice: sales.EUR(800)},
}, sales.TierGold, 6650, 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
o, err := sales.NewOrder("o-1", "c-1", tc.lines)
if err != nil {
t.Fatal(err)
}
q, err := policy.Quote(o, tc.tier, []sales.Promotion{promo})
if err != nil {
t.Fatal(err)
}
if q.Total.Minor != tc.wantTotal || q.Shipping.Minor != tc.wantShip {
t.Fatalf("total=%d shipping=%d, want %d and %d", q.Total.Minor, q.Shipping.Minor, tc.wantTotal, tc.wantShip)
}
})
}
}
func TestPricingService_RejectsMixedCurrencies(t *testing.T) {
o, _ := sales.NewOrder("o-2", "c-1", []sales.Line{
{SKU: "MUG", Quantity: 1, UnitPrice: sales.EUR(1200)},
{SKU: "TEA", Quantity: 1, UnitPrice: sales.Money{Minor: 900, Currency: "USD"}},
})
if _, err := (sales.PricingService{}).Quote(o, sales.TierStandard, nil); err == nil {
t.Fatal("want currency mismatch error")
}
}application service با adapterهای درونحافظه تست میشود. هماهنگسازی را میسنجد: چه ذخیره شد، چه به outbox رفت، چه شارژ و چه void شد، و مسابقهٔ درخواست تکراری:
package command_test
import (
"context"
"errors"
"testing"
"time"
"academy/domain-application-infrastructure-services/adapters/memory"
"academy/domain-application-infrastructure-services/app/command"
"academy/domain-application-infrastructure-services/sales"
)
// An application service is tested with in-memory adapters (fakes): we check
// orchestration (what was saved, which events, which side effects), not prices.
func newHandler() (command.PlaceOrderHandler, *memory.Store, *memory.Payments) {
store, pay := memory.NewStore(), memory.NewPayments()
return command.PlaceOrderHandler{
UoW: store, Orders: store,
Catalog: memory.Catalog{"MUG": sales.EUR(1200)},
Customers: memory.Customers{},
Promotions: memory.Promotions{},
Payments: pay,
Clock: memory.FixedClock{T: time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)},
Pricing: sales.PricingService{GoldPercentOff: 5, FreeShippingFrom: 5000, FlatShippingMinor: 495},
}, store, pay
}
var cmd = command.PlaceOrder{OrderID: "o-1", CustomerID: "c-1", Items: []command.Item{{SKU: "MUG", Quantity: 1}}, PaymentToken: "pm"}
func TestPlaceOrder_SavesOrderAndOutboxesEvent(t *testing.T) {
h, store, pay := newHandler()
res, err := h.Handle(context.Background(), cmd)
if err != nil {
t.Fatal(err)
}
if res.Total.Minor != 1695 {
t.Fatalf("total = %d", res.Total.Minor)
}
o, err := store.Get(context.Background(), "o-1")
if err != nil || o.Status() != sales.Placed {
t.Fatalf("order not placed: %v", err)
}
ev := store.Outboxed()
if len(ev) != 1 || ev[0].EventName() != "OrderPlaced" {
t.Fatalf("outbox = %v", ev)
}
if _, ok := pay.Authorized["order-o-1"]; !ok {
t.Fatal("payment not authorized with the order idempotency key")
}
}
func TestPlaceOrder_IsIdempotent(t *testing.T) {
h, store, pay := newHandler()
_, _ = h.Handle(context.Background(), cmd)
res, err := h.Handle(context.Background(), cmd)
if err != nil || !res.Replay {
t.Fatalf("replay=%v err=%v", res.Replay, err)
}
if len(store.Outboxed()) != 1 || len(pay.Authorized) != 1 {
t.Fatal("a replayed command must not publish or charge twice")
}
}
func TestPlaceOrder_VoidsPaymentWhenCommitFails(t *testing.T) {
h, store, pay := newHandler()
store.FailCommit = errors.New("connection reset")
if _, err := h.Handle(context.Background(), cmd); err == nil {
t.Fatal("want error")
}
if len(pay.Voided) != 1 || len(store.Outboxed()) != 0 {
t.Fatalf("voided=%v outbox=%v", pay.Voided, store.Outboxed())
}
}
func TestPlaceOrder_DomainRuleComesBackUnchanged(t *testing.T) {
h, _, pay := newHandler()
bad := cmd
bad.Items = []command.Item{{SKU: "MUG", Quantity: 99}}
if _, err := h.Handle(context.Background(), bad); !errors.Is(err, sales.ErrBadQuantity) {
t.Fatalf("err = %v", err)
}
if len(pay.Authorized) != 0 {
t.Fatal("no payment may be attempted for an invalid order")
}
}
// Two requests with the same OrderID race: both pass the idempotency read,
// the second loses on the primary key. It must NOT void the shared payment.
func TestPlaceOrder_LosingTheDuplicateRaceDoesNotVoid(t *testing.T) {
h, store, pay := newHandler()
winner, _ := sales.NewOrder("o-1", "c-1", []sales.Line{{SKU: "MUG", Quantity: 1, UnitPrice: sales.EUR(1200)}})
q, _ := h.Pricing.Quote(winner, sales.TierStandard, nil)
_ = winner.Place(q, "auth_order-o-1", time.Now())
// The idempotency read sees nothing, then the winner commits before us.
h.Orders = &racingRepo{OrderRepository: store, beforeFirstGet: func() { _ = store.Add(context.Background(), winner) }}
res, err := h.Handle(context.Background(), cmd)
if err != nil || !res.Replay {
t.Fatalf("replay=%v err=%v", res.Replay, err)
}
if len(pay.Voided) != 0 {
t.Fatalf("voided the winner's payment: %v", pay.Voided)
}
}
// racingRepo reports "not found" on the first Get and lets the winner commit.
type racingRepo struct {
sales.OrderRepository
beforeFirstGet func()
}
func (r *racingRepo) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
if r.beforeFirstGet != nil {
r.beforeFirstGet()
r.beforeFirstGet = nil
return nil, sales.ErrOrderNotFound
}
return r.OrderRepository.Get(ctx, id)
}adapter زیرساخت یک contract test روی httptest.Server میگیرد. قالب سیم و ترجمهٔ خطا را میسنجد، نه use case را:
package stripe_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/domain-application-infrastructure-services/adapters/stripe"
"academy/domain-application-infrastructure-services/app"
"academy/domain-application-infrastructure-services/sales"
)
// An adapter is tested against the wire contract, not against the use case.
func TestGateway_AuthorizeSendsContract(t *testing.T) {
var gotKey, gotBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotKey = r.Header.Get("Idempotency-Key")
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
_, _ = io.WriteString(w, `{"id":"pi_123","status":"requires_capture"}`)
}))
defer srv.Close()
g := stripe.Gateway{BaseURL: srv.URL, APIKey: "sk_test", HTTP: srv.Client()}
ref, err := g.Authorize(context.Background(), "order-o-1", sales.EUR(1695), "pm_card_visa")
if err != nil || ref != "pi_123" {
t.Fatalf("ref=%q err=%v", ref, err)
}
if gotKey != "order-o-1" {
t.Fatalf("Idempotency-Key = %q", gotKey)
}
for _, want := range []string{"amount=1695", "currency=eur", "capture_method=manual"} {
if !strings.Contains(gotBody, want) {
t.Fatalf("body %q lacks %q", gotBody, want)
}
}
}
func TestGateway_TranslatesCardError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPaymentRequired)
_, _ = io.WriteString(w, `{"error":{"type":"card_error","code":"card_declined"}}`)
}))
defer srv.Close()
g := stripe.Gateway{BaseURL: srv.URL, HTTP: srv.Client()}
if _, err := g.Authorize(context.Background(), "k", sales.EUR(100), "pm"); !errors.Is(err, app.ErrPaymentDeclined) {
t.Fatalf("err = %v, want ErrPaymentDeclined", err)
}
}قاعدهٔ وابستگی به شکل تست:
package sales_test
import (
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"testing"
)
// The dependency rule as a test: the domain imports no layer above it and no
// I/O package. Breaking the rule fails CI, not a code review.
func TestDomainImportsNothingOutward(t *testing.T) {
forbidden := []string{"/app", "/adapters", "database/sql", "net/http", "log/slog", "os"}
files, _ := filepath.Glob("*.go")
for _, f := range files {
if strings.HasSuffix(f, "_test.go") {
continue
}
src, err := os.ReadFile(f)
if err != nil {
t.Fatal(err)
}
ast, err := parser.ParseFile(token.NewFileSet(), f, src, parser.ImportsOnly)
if err != nil {
t.Fatal(err)
}
for _, imp := range ast.Imports {
path := strings.Trim(imp.Path.Value, `"`)
for _, bad := range forbidden {
if path == bad || strings.HasSuffix(path, bad) || strings.Contains(path, bad+"/") {
t.Errorf("%s imports %s: the domain must not depend on it", f, path)
}
}
}
}
}غلط: سرویس چاق
// Package wrong shows the shape this chapter argues against: one "service"
// that is controller, use case, pricing policy, SQL and payment client at once.
package wrong
import (
"bytes"
"context"
"database/sql"
"fmt"
"net/http"
"time"
)
// OrderService is a fat application service. Every rule below is a business
// rule living in the wrong layer, and every dependency is concrete.
type OrderService struct {
DB *sql.DB
}
// Item is a requested line.
type Item struct {
SKU string
Quantity int
}
// PlaceOrder mixes four kinds of code; see the comments.
func (s OrderService) PlaceOrder(ctx context.Context, customerID string, items []Item) (int64, error) {
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
var total int64
for _, it := range items {
var price int64
// infrastructure inside the use case: raw SQL against another context's table
if err := tx.QueryRowContext(ctx, `SELECT price_minor FROM catalog_products WHERE sku = $1`, it.SKU).Scan(&price); err != nil {
return 0, err
}
line := price * int64(it.Quantity)
if it.SKU == "MUG" && it.Quantity >= 3 { // pricing policy hard-coded in the service
line = line * 90 / 100
}
total += line
}
var tier string
_ = tx.QueryRowContext(ctx, `SELECT tier FROM identity_customers WHERE id = $1`, customerID).Scan(&tier)
if tier == "gold" { // another business rule
total = total * 95 / 100
}
if total < 5000 {
total += 495
}
// I/O to a payment provider while the transaction holds locks and a connection
body := fmt.Sprintf(`amount=%d¤cy=eur&capture_method=manual`, total)
resp, err := http.Post("https://api.stripe.com/v1/payment_intents", "application/x-www-form-urlencoded", bytes.NewBufferString(body))
if err != nil {
return 0, err
}
resp.Body.Close()
var id int64
err = tx.QueryRowContext(ctx,
`INSERT INTO sales_orders (customer_id, status, total_minor, placed_at) VALUES ($1, 'placed', $2, $3) RETURNING id`,
customerID, total, time.Now()). // hidden dependency on the wall clock
Scan(&id)
if err != nil {
return 0, err
}
return id, tx.Commit() // no event: Fulfilment and Billing never hear about it
}نگاه Go
- interface مال مصرفکننده است. interfaceهای ضمنی Go، port را طبیعی میکنند:
app.PaymentGatewayهمانجا اعلام میشود که استفاده میشود وstripe.Gatewayبیآنکه چیزی import کند آن را برآورده میکند. Go Code Review Comments هم همین را میگوید: interfaceها "generally belong in the package that uses values of the interface type". - چیدمان پکیج همان معماری است. کامپایلر چرخهها را میگیرد و
deps_test.goجهت را، تاsalesچیزی رو به بیرون import نکند. ابزارهایی مثلgo-arch-lintیاdepguard(در golangci-lint) همین را در CI انجام میدهند (Project Layout & Linting). - decorator جنریک. از Go 1.18 به بعد
decorator.Handler[C, R]اجازه میدهد یکLoggingدور هر handlerی پیچیده شود. Wild Workouts همین ایده را باdecorator.CommandHandler[C]دارد. context.Contextلغو و مهلت درخواست را حمل میکند، از adapter HTTP، از میان use case، تاdatabase/sqlو client استرایپ. کیسهای برای وابستگیها نیست؛ portها فیلدهای struct هستند.- container DI لازم نیست.
main.goریشهٔ ترکیب است. فقط وقتی سراغgoogle/wireبروید که سیمکشی دستی دیگر در یک صفحه جا نشود. تست با fake در Mocking & DI in Go آمده.
Laravel
همان use case در یک ماژول Laravel 13 (app/Modules/Sales/{Domain,Application,Infrastructure}) با نحو PHP 8.4. کد PHP بازبینی شده ولی اجرا نشده (روی ماشین نویسنده PHP نصب نیست).
دامنه: PHP ساده، بدون Eloquent و facade
<?php
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
/**
* Aggregate root. A plain PHP class: no Eloquent, no facades, no now().
* The repository maps it to tables; the application service drives it.
*/
final class Order
{
private string $status = 'draft';
private ?Money $total = null;
private ?string $paymentRef = null;
private ?DateTimeImmutable $placedAt = null;
/** @var list<object> */
private array $events = [];
/** @param list<OrderLine> $lines */
public function __construct(
public readonly string $id,
public readonly string $customerId,
private readonly array $lines,
) {
if ($lines === []) {
throw new OrderRuleViolated('an order needs at least one line');
}
}
/**
* Rebuild a stored order without re-running place() or raising events.
* Only repositories call this.
*
* @param list<OrderLine> $lines
*/
public static function reconstitute(string $id, string $customerId, array $lines, string $status, ?Money $total, ?string $paymentRef, ?DateTimeImmutable $placedAt): self
{
$order = new self($id, $customerId, $lines);
[$order->status, $order->total, $order->paymentRef, $order->placedAt] = [$status, $total, $paymentRef, $placedAt];
return $order;
}
public function place(Quote $quote, string $paymentRef, DateTimeImmutable $now): void
{
if ($this->status !== 'draft') {
throw new OrderRuleViolated('the order has already been placed');
}
if ($quote->orderId !== $this->id) {
throw new OrderRuleViolated('the quote was made for another order');
}
[$this->status, $this->total, $this->paymentRef, $this->placedAt] = ['placed', $quote->total, $paymentRef, $now];
$this->events[] = new OrderPlaced($this->id, $this->customerId, $quote->total, $paymentRef, $now);
}
/** @return list<object> recorded events, cleared on read */
public function pullEvents(): array
{
[$events, $this->events] = [$this->events, []];
return $events;
}
/** @return list<OrderLine> */
public function lines(): array
{
return $this->lines;
}
public function status(): string
{
return $this->status;
}
public function total(): ?Money
{
return $this->total;
}
public function paymentRef(): ?string
{
return $this->paymentRef;
}
public function placedAt(): ?DateTimeImmutable
{
return $this->placedAt;
}
}<?php
namespace App\Modules\Sales\Domain;
final readonly class OrderLine
{
public function __construct(
public string $sku,
public int $quantity,
public Money $unitPrice,
) {
if ($quantity < 1 || $quantity > 50) {
throw new OrderRuleViolated('quantity must be between 1 and 50');
}
}
}<?php
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
use DateTimeInterface;
use JsonSerializable;
/** Domain event: a plain PHP object, no Laravel traits, no broadcasting. */
final readonly class OrderPlaced implements JsonSerializable
{
public function __construct(
public string $orderId,
public string $customerId,
public Money $total,
public string $paymentRef,
public DateTimeImmutable $placedAt,
) {}
/** @return array<string, mixed> the published-language payload */
public function jsonSerialize(): array
{
return [
'order_id' => $this->orderId,
'customer_id' => $this->customerId,
'total_minor' => $this->total->minor,
'currency' => $this->total->currency,
'payment_ref' => $this->paymentRef,
'placed_at' => $this->placedAt->format(DateTimeInterface::ATOM),
];
}
}<?php
namespace App\Modules\Sales\Domain;
/**
* DOMAIN service. Pricing combines lines, the customer's tier and the active
* promotions, so it belongs to no single entity. Stateless, no I/O, no
* facades: the same input always gives the same Quote.
*/
final readonly class PricingService
{
public function __construct(
private int $goldPercentOff = 5,
private int $freeShippingFromMinor = 5000,
private int $flatShippingMinor = 495,
) {}
/** @param list<Promotion> $promotions */
public function quote(Order $order, CustomerTier $tier, array $promotions): Quote
{
$currency = $order->lines()[0]->unitPrice->currency;
$subtotal = Money::zero($currency);
$discount = Money::zero($currency);
foreach ($order->lines() as $line) {
$lineTotal = $line->unitPrice->times($line->quantity);
$subtotal = $subtotal->add($lineTotal);
$best = 0;
foreach ($promotions as $promo) {
if ($promo->sku === $line->sku && $line->quantity >= $promo->minQty) {
$best = max($best, $promo->percentOff);
}
}
$discount = $discount->add($lineTotal->percentOff($best));
}
if ($tier === CustomerTier::Gold) {
$discount = $discount->add($subtotal->sub($discount)->percentOff($this->goldPercentOff));
}
$net = $subtotal->sub($discount);
$shipping = $net->minor >= $this->freeShippingFromMinor
? Money::zero($currency)
: new Money($this->flatShippingMinor, $currency);
return new Quote($order->id, $subtotal, $discount, $shipping, $net->add($shipping));
}
}<?php
namespace App\Modules\Sales\Domain;
/** Port owned by the domain; EloquentOrderRepository implements it. */
interface OrderRepository
{
public function find(string $id): ?Order;
/** @throws DuplicateOrder when the id is already taken */
public function add(Order $order): void;
}کاربرد: portها، use case، query، decorator، job
<?php
namespace App\Modules\Sales\Application\Ports;
use App\Modules\Sales\Domain\Money;
/** Infrastructure-service port, in the use case's own words. */
interface PaymentGateway
{
/** @throws PaymentDeclined */
public function authorize(string $idempotencyKey, Money $amount, string $paymentToken): string;
public function void(string $reference): void;
}<?php
namespace App\Modules\Sales\Application\Ports;
interface UnitOfWork
{
/**
* Run $work in one transaction: commit on return, roll back on exception.
*
* @template T
*
* @param callable(): T $work
* @return T
*/
public function run(callable $work): mixed;
}<?php
namespace App\Modules\Sales\Application;
/** Input DTO (command). Built by the Form Request, a job or a console command. */
final readonly class PlaceOrder
{
/** @param list<array{sku: string, quantity: int}> $items */
public function __construct(
public string $orderId,
public string $customerId,
public array $items,
public string $paymentToken,
) {}
}<?php
namespace App\Modules\Sales\Application;
use App\Modules\Sales\Application\Ports\Catalog;
use App\Modules\Sales\Application\Ports\Clock;
use App\Modules\Sales\Application\Ports\Customers;
use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Application\Ports\Promotions;
use App\Modules\Sales\Application\Ports\UnitOfWork;
use App\Modules\Sales\Domain\DuplicateOrder;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\PricingService;
use Throwable;
/**
* APPLICATION service (use case). It orchestrates: read inputs through
* ports, let the domain decide, call the payment port outside the
* transaction, save aggregate + events in one transaction. No pricing rule,
* no SQL, no HTTP and no facade appears here.
*/
final readonly class PlaceOrderHandler implements PlacesOrders
{
public function __construct(
private OrderRepository $orders,
private UnitOfWork $uow,
private Outbox $outbox,
private Catalog $catalog,
private Customers $customers,
private Promotions $promotions,
private PaymentGateway $payments,
private Clock $clock,
private PricingService $pricing,
) {}
public function handle(PlaceOrder $command): PlaceOrderResult
{
// 1. Idempotency: a repeated command returns the first result.
if ($existing = $this->orders->find($command->orderId)) {
return new PlaceOrderResult($existing->id, $existing->total(), replay: true);
}
// 2. Inputs through ports.
$prices = $this->catalog->unitPrices(array_column($command->items, 'sku'));
$lines = [];
foreach ($command->items as $item) {
$price = $prices[$item['sku']] ?? throw new OrderRuleViolated("unknown sku {$item['sku']}");
$lines[] = new OrderLine($item['sku'], $item['quantity'], $price);
}
$now = $this->clock->now();
// 3. Domain decides.
$order = new Order($command->orderId, $command->customerId, $lines);
$quote = $this->pricing->quote(
$order,
$this->customers->tierOf($command->customerId),
$this->promotions->activeAt($now),
);
// 4. External side effect outside the DB transaction.
$ref = $this->payments->authorize("order-{$order->id}", $quote->total, $command->paymentToken);
try {
$order->place($quote, $ref, $now);
// 5. One transaction: aggregate + outbox rows.
$this->uow->run(function () use ($order): void {
$this->orders->add($order);
$this->outbox->append(...$order->pullEvents());
});
} catch (DuplicateOrder) {
// A concurrent request with the same id won the race. Both used the
// same idempotency key, so they share ONE authorization: voiding it
// would cancel the winner's payment. Return the winner's result.
$winner = $this->orders->find($command->orderId);
return new PlaceOrderResult($winner->id, $winner->total(), replay: true);
} catch (Throwable $e) {
$this->payments->void($ref); // compensate what SQL cannot roll back
throw $e;
}
return new PlaceOrderResult($order->id, $quote->total);
}
}<?php
namespace App\Modules\Sales\Application\Queries;
/**
* Query handler (CQS on the read side): no aggregate, no repository, no
* transaction, no events. It returns DTO arrays shaped for the screen.
*/
final readonly class CustomerOrdersHandler
{
public function __construct(private OrderSummaries $readModel) {}
public function handle(CustomerOrders $query): array
{
return $this->readModel->forCustomer($query->customerId, min(max($query->limit, 1), 100));
}
}<?php
namespace App\Modules\Sales\Application\Middleware;
use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlaceOrderResult;
use App\Modules\Sales\Application\PlacesOrders;
use Psr\Log\LoggerInterface;
use Throwable;
/**
* Decorator: logging and timing around the use case, registered with
* $this->app->extend(). The correlation id comes from Laravel Context,
* which appends it to every log entry automatically.
*/
final readonly class LogsPlaceOrder implements PlacesOrders
{
public function __construct(private PlacesOrders $inner, private LoggerInterface $log) {}
public function handle(PlaceOrder $command): PlaceOrderResult
{
$start = hrtime(true);
try {
$result = $this->inner->handle($command);
$this->log->info('command handled', ['command' => 'PlaceOrder', 'ok' => true, 'ms' => (hrtime(true) - $start) / 1e6]);
return $result;
} catch (Throwable $e) {
$this->log->warning('command failed', ['command' => 'PlaceOrder', 'error' => $e::class]);
throw $e;
}
}
}job صف یک adapter راننده دیگر است. همان use case را بعداً و روی یک worker صدا میزند:
<?php
namespace App\Modules\Sales\Application\Jobs;
use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlacesOrders;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
/**
* A queued job is another DRIVING adapter: it carries the same command DTO
* and calls the same use case, just later and on a worker (B2B CSV imports).
* Retrying is safe because PlaceOrder is idempotent on orderId.
*/
final class PlaceOrderInBackground implements ShouldQueue
{
use Queueable;
public int $tries = 5;
public function __construct(public PlaceOrder $command) {}
public function handle(PlacesOrders $useCase): void
{
$useCase->handle($this->command);
}
/** @return list<int> */
public function backoff(): array
{
return [5, 30, 120];
}
}لبه: Form Request، controller، correlation id
<?php
namespace App\Http\Requests;
use App\Modules\Sales\Application\PlaceOrder;
use Illuminate\Foundation\Http\FormRequest;
/**
* The edge: authorization and SHAPE validation. Business rules (max quantity,
* pricing, "already placed") stay in the domain; this class only refuses
* requests that are not even well-formed.
*/
class PlaceOrderRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->can('place-orders') ?? false;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'items' => ['required', 'array', 'min:1'],
'items.*.sku' => ['required', 'string', 'max:64'],
'items.*.quantity' => ['required', 'integer', 'min:1'],
'payment_token' => ['required', 'string'],
];
}
public function toCommand(): PlaceOrder
{
return new PlaceOrder(
orderId: (string) $this->header('Idempotency-Key'),
customerId: (string) $this->user()->getAuthIdentifier(),
items: array_map(
fn (array $i) => ['sku' => $i['sku'], 'quantity' => (int) $i['quantity']],
$this->validated('items'),
),
paymentToken: $this->validated('payment_token'),
);
}
}<?php
namespace App\Http\Controllers;
use App\Http\Requests\PlaceOrderRequest;
use App\Modules\Sales\Application\PlacesOrders;
use App\Modules\Sales\Application\Ports\PaymentDeclined;
use App\Modules\Sales\Domain\OrderRuleViolated;
use Illuminate\Http\JsonResponse;
/** Driving adapter: HTTP in, command DTO to the use case, HTTP out. */
class PlaceOrderController
{
public function __invoke(PlaceOrderRequest $request, PlacesOrders $useCase): JsonResponse
{
abort_unless($request->hasHeader('Idempotency-Key'), 428, 'Idempotency-Key header required');
try {
$result = $useCase->handle($request->toCommand());
} catch (OrderRuleViolated $e) {
return response()->json(['message' => $e->getMessage()], 422);
} catch (PaymentDeclined $e) {
return response()->json(['message' => 'payment declined'], 402);
}
return response()->json([
'order_id' => $result->orderId,
'total_minor' => $result->total->minor,
'currency' => $result->total->currency,
], $result->replay ? 200 : 201);
}
}<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
/**
* Cross-cutting concern at the edge. Context data is appended to every log
* entry and travels with queued jobs dispatched during this request.
*/
class AssignCorrelationId
{
public function handle(Request $request, Closure $next): Response
{
Context::add('correlation_id', $request->header('X-Correlation-Id') ?? (string) Str::uuid());
return $next($request);
}
}زیرساخت: Eloquent، unit of work، outbox، Stripe، ساعت
<?php
namespace App\Modules\Sales\Infrastructure;
use App\Modules\Sales\Domain\DuplicateOrder;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderRepository;
use Illuminate\Database\UniqueConstraintViolationException;
/** Adapter: maps the aggregate to two tables with Eloquent. */
final class EloquentOrderRepository implements OrderRepository
{
public function find(string $id): ?Order
{
$row = OrderRecord::with('lines')->find($id);
if ($row === null) {
return null;
}
$lines = $row->lines
->map(fn (OrderLineRecord $l) => new OrderLine($l->sku, $l->quantity, new Money($l->unit_minor, $row->currency)))
->all();
return Order::reconstitute(
$row->id,
$row->customer_id,
$lines,
$row->status,
$row->total_minor === null ? null : new Money($row->total_minor, $row->currency),
$row->payment_ref,
$row->placed_at,
);
}
public function add(Order $order): void
{
try {
$this->insert($order);
} catch (UniqueConstraintViolationException) {
throw new DuplicateOrder($order->id); // SQLSTATE 23505 / MySQL 1062
}
}
private function insert(Order $order): void
{
OrderRecord::create([
'id' => $order->id,
'customer_id' => $order->customerId,
'status' => $order->status(),
'total_minor' => $order->total()?->minor,
'currency' => $order->total()?->currency,
'payment_ref' => $order->paymentRef(),
'placed_at' => $order->placedAt(),
]);
foreach ($order->lines() as $i => $line) {
OrderLineRecord::create([
'order_id' => $order->id,
'position' => $i,
'sku' => $line->sku,
'quantity' => $line->quantity,
'unit_minor' => $line->unitPrice->minor,
]);
}
}
}<?php
namespace App\Modules\Sales\Infrastructure;
use App\Modules\Sales\Application\Ports\UnitOfWork;
use Illuminate\Database\ConnectionInterface;
final readonly class DatabaseUnitOfWork implements UnitOfWork
{
public function __construct(private ConnectionInterface $db) {}
public function run(callable $work): mixed
{
// Same as DB::transaction(): commit on return, roll back on exception.
return $this->db->transaction(fn () => $work());
}
}<?php
namespace App\Modules\Sales\Infrastructure;
use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Domain\OrderPlaced;
use Illuminate\Database\ConnectionInterface;
/** Writes integration-ready rows; a relay job publishes them after commit. */
final readonly class DatabaseOutbox implements Outbox
{
public function __construct(private ConnectionInterface $db) {}
public function append(object ...$events): void
{
foreach ($events as $event) {
$this->db->table('outbox')->insert([
'event_name' => match ($event::class) {
OrderPlaced::class => 'sales.order.placed.v1',
default => $event::class,
},
'payload' => json_encode($event, JSON_THROW_ON_ERROR),
'created_at' => now(),
]);
}
}
}<?php
namespace App\Modules\Sales\Infrastructure;
use App\Modules\Sales\Application\Ports\PaymentDeclined;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Domain\Money;
use Illuminate\Support\Facades\Http;
/**
* Infrastructure service: Stripe's vocabulary (PaymentIntent, capture_method,
* Idempotency-Key) stays in this class. Facades are fine HERE.
*/
final readonly class StripePaymentGateway implements PaymentGateway
{
public function __construct(private string $secret, private string $baseUrl = 'https://api.stripe.com') {}
public function authorize(string $idempotencyKey, Money $amount, string $paymentToken): string
{
$response = Http::withToken($this->secret)
->withHeaders(['Idempotency-Key' => $idempotencyKey])
->asForm()
->timeout(10)
->post("{$this->baseUrl}/v1/payment_intents", [
'amount' => $amount->minor,
'currency' => strtolower($amount->currency),
'payment_method' => $paymentToken,
'capture_method' => 'manual',
'confirm' => 'true',
]);
if ($response->status() === 402 || $response->json('error.type') === 'card_error') {
throw new PaymentDeclined($response->json('error.code') ?? 'declined');
}
$response->throw();
return $response->json('id');
}
public function void(string $reference): void
{
Http::withToken($this->secret)
->withHeaders(['Idempotency-Key' => "void-{$reference}"])
->asForm()
->post("{$this->baseUrl}/v1/payment_intents/{$reference}/cancel")
->throw();
}
}<?php
namespace App\Modules\Sales\Infrastructure;
use App\Modules\Sales\Application\Ports\Clock;
use DateTimeImmutable;
use Illuminate\Support\Facades\Date;
final class SystemClock implements Clock
{
public function now(): DateTimeImmutable
{
// Date::now() honours Carbon test helpers such as $this->travelTo().
return Date::now()->toDateTimeImmutable();
}
}سیمکشی: service provider همان ریشهٔ ترکیب است
<?php
namespace App\Providers;
use App\Modules\Sales\Application\Middleware\LogsPlaceOrder;
use App\Modules\Sales\Application\PlaceOrderHandler;
use App\Modules\Sales\Application\PlacesOrders;
use App\Modules\Sales\Application\Ports\Catalog;
use App\Modules\Sales\Application\Ports\Clock;
use App\Modules\Sales\Application\Ports\Customers;
use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Application\Ports\Promotions;
use App\Modules\Sales\Application\Ports\UnitOfWork;
use App\Modules\Sales\Application\Queries\OrderSummaries;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\PricingService;
use App\Modules\Sales\Infrastructure\DatabaseOrderSummaries;
use App\Modules\Sales\Infrastructure\DatabaseOutbox;
use App\Modules\Sales\Infrastructure\DatabasePricingInputs;
use App\Modules\Sales\Infrastructure\DatabaseUnitOfWork;
use App\Modules\Sales\Infrastructure\EloquentOrderRepository;
use App\Modules\Sales\Infrastructure\StripePaymentGateway;
use App\Modules\Sales\Infrastructure\SystemClock;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Psr\Log\LoggerInterface;
/** Composition root for the Sales module: ports -> adapters. */
class SalesServiceProvider extends ServiceProvider
{
/** Simple port => adapter bindings. */
public array $bindings = [
OrderRepository::class => EloquentOrderRepository::class,
UnitOfWork::class => DatabaseUnitOfWork::class,
Outbox::class => DatabaseOutbox::class,
Clock::class => SystemClock::class,
Catalog::class => DatabasePricingInputs::class,
Customers::class => DatabasePricingInputs::class,
Promotions::class => DatabasePricingInputs::class,
PlacesOrders::class => PlaceOrderHandler::class,
OrderSummaries::class => DatabaseOrderSummaries::class,
];
public function register(): void
{
$this->app->singleton(PricingService::class, fn () => new PricingService(
goldPercentOff: config('sales.gold_percent_off', 5),
freeShippingFromMinor: config('sales.free_shipping_from_minor', 5000),
flatShippingMinor: config('sales.flat_shipping_minor', 495),
));
$this->app->singleton(PaymentGateway::class, fn () => new StripePaymentGateway(
secret: (string) config('services.stripe.secret'),
));
// Cross-cutting concern as a decorator around the use case.
$this->app->extend(PlacesOrders::class, fn (PlacesOrders $useCase, Application $app) => new LogsPlaceOrder($useCase, $app->make(LoggerInterface::class)));
}
}تستها
domain service با یک TestCase ساده از PHPUnit اجرا میشود و هیچ اپلیکیشن لاراولی بالا نمیآید:
<?php
namespace Tests\Unit;
use App\Modules\Sales\Domain\CustomerTier;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\PricingService;
use App\Modules\Sales\Domain\Promotion;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
/** Pure unit test: plain PHPUnit TestCase, no Laravel app, no database. */
final class PricingServiceTest extends TestCase
{
public static function cases(): array
{
$mug = fn (int $q) => new OrderLine('MUG', $q, Money::eur(1200));
return [
'small standard order pays shipping' => [[$mug(1)], CustomerTier::Standard, 1695],
'promotion from 3 mugs' => [[$mug(3)], CustomerTier::Standard, 3240 + 495],
'gold on top of promotion, free shipping' => [[$mug(5), new OrderLine('TEA', 2, Money::eur(800))], CustomerTier::Gold, 6650],
];
}
#[DataProvider('cases')]
public function test_quote(array $lines, CustomerTier $tier, int $expectedTotal): void
{
$order = new Order('o-1', 'c-1', $lines);
$quote = (new PricingService)->quote($order, $tier, [new Promotion('MUG3', 'MUG', 3, 10)]);
$this->assertSame($expectedTotal, $quote->total->minor);
}
}application service با fakeهایی از جنس کلاس بینام، هماهنگسازی، idempotency، جبران و مسابقهٔ تکراری را میسنجد:
<?php
namespace Tests\Unit;
use App\Modules\Sales\Application\PlaceOrder;
use App\Modules\Sales\Application\PlaceOrderHandler;
use App\Modules\Sales\Application\Ports\Catalog;
use App\Modules\Sales\Application\Ports\Clock;
use App\Modules\Sales\Application\Ports\Customers;
use App\Modules\Sales\Application\Ports\Outbox;
use App\Modules\Sales\Application\Ports\PaymentGateway;
use App\Modules\Sales\Application\Ports\Promotions;
use App\Modules\Sales\Application\Ports\UnitOfWork;
use App\Modules\Sales\Domain\CustomerTier;
use App\Modules\Sales\Domain\DuplicateOrder;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderPlaced;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\PricingService;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use RuntimeException;
/** Application service with fakes: we assert orchestration, not prices. */
final class PlaceOrderHandlerTest extends TestCase
{
private object $orders;
private object $outbox;
private object $payments;
private object $uow;
protected function setUp(): void
{
$this->orders = new class implements OrderRepository
{
public array $saved = [];
public ?Order $racer = null; // simulates a concurrent winner
public function find(string $id): ?Order
{
return $this->saved[$id] ?? null;
}
public function add(Order $order): void
{
if ($this->racer !== null) {
$this->saved[$this->racer->id] = $this->racer;
throw new DuplicateOrder($order->id);
}
$this->saved[$order->id] = $order;
}
};
$this->outbox = new class implements Outbox
{
public array $events = [];
public function append(object ...$events): void
{
array_push($this->events, ...$events);
}
};
$this->payments = new class implements PaymentGateway
{
public array $authorized = [];
public array $voided = [];
public function authorize(string $idempotencyKey, Money $amount, string $paymentToken): string
{
$this->authorized[$idempotencyKey] = $amount;
return "pi_{$idempotencyKey}";
}
public function void(string $reference): void
{
$this->voided[] = $reference;
}
};
$this->uow = new class implements UnitOfWork
{
public bool $fail = false;
public function run(callable $work): mixed
{
$result = $work();
if ($this->fail) {
throw new RuntimeException('commit failed');
}
return $result;
}
};
}
private function handler(): PlaceOrderHandler
{
$inputs = new class implements Catalog, Customers, Promotions
{
public function unitPrices(array $skus): array
{
return ['MUG' => Money::eur(1200)];
}
public function tierOf(string $customerId): CustomerTier
{
return CustomerTier::Standard;
}
public function activeAt(DateTimeImmutable $at): array
{
return [];
}
};
$clock = new class implements Clock
{
public function now(): DateTimeImmutable
{
return new DateTimeImmutable('2026-11-25T10:00:00Z');
}
};
return new PlaceOrderHandler($this->orders, $this->uow, $this->outbox, $inputs, $inputs, $inputs, $this->payments, $clock, new PricingService);
}
private function command(int $quantity = 1): PlaceOrder
{
return new PlaceOrder('o-1', 'c-1', [['sku' => 'MUG', 'quantity' => $quantity]], 'pm_card_visa');
}
public function test_places_order_and_outboxes_event(): void
{
$result = $this->handler()->handle($this->command());
$this->assertSame(1695, $result->total->minor);
$this->assertSame('placed', $this->orders->saved['o-1']->status());
$this->assertInstanceOf(OrderPlaced::class, $this->outbox->events[0]);
$this->assertArrayHasKey('order-o-1', $this->payments->authorized);
}
public function test_is_idempotent(): void
{
$this->handler()->handle($this->command());
$again = $this->handler()->handle($this->command());
$this->assertTrue($again->replay);
$this->assertCount(1, $this->outbox->events);
$this->assertCount(1, $this->payments->authorized);
}
public function test_voids_payment_when_commit_fails(): void
{
$this->uow->fail = true;
try {
$this->handler()->handle($this->command());
$this->fail('expected exception');
} catch (RuntimeException) {
$this->assertSame(['pi_order-o-1'], $this->payments->voided);
}
}
public function test_domain_rule_is_not_charged(): void
{
$this->expectException(OrderRuleViolated::class);
try {
$this->handler()->handle($this->command(quantity: 99));
} finally {
$this->assertSame([], $this->payments->authorized);
}
}
public function test_losing_the_duplicate_race_does_not_void(): void
{
$winner = new Order('o-1', 'c-1', [new OrderLine('MUG', 1, Money::eur(1200))]);
$winner->place((new PricingService)->quote($winner, CustomerTier::Standard, []), 'pi_order-o-1', new DateTimeImmutable);
$this->orders->racer = $winner;
$result = $this->handler()->handle($this->command());
$this->assertTrue($result->replay);
$this->assertSame([], $this->payments->voided);
}
}قرارداد adapter با Http::fake() و Http::assertSent() بررسی میشود:
<?php
namespace Tests\Integration;
use App\Modules\Sales\Application\Ports\PaymentDeclined;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Infrastructure\StripePaymentGateway;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
/** Adapter test: the wire contract with Stripe, faked at the HTTP level. */
final class StripePaymentGatewayTest extends TestCase
{
public function test_authorize_sends_idempotency_key_and_manual_capture(): void
{
Http::fake(['api.stripe.com/*' => Http::response(['id' => 'pi_123', 'status' => 'requires_capture'])]);
$ref = (new StripePaymentGateway('sk_test'))->authorize('order-o-1', Money::eur(1695), 'pm_card_visa');
$this->assertSame('pi_123', $ref);
Http::assertSent(fn (Request $r) => $r->hasHeader('Idempotency-Key', 'order-o-1')
&& (int) $r['amount'] === 1695
&& $r['capture_method'] === 'manual');
}
public function test_card_error_becomes_payment_declined(): void
{
Http::fake(['api.stripe.com/*' => Http::response(['error' => ['type' => 'card_error', 'code' => 'card_declined']], 402)]);
$this->expectException(PaymentDeclined::class);
(new StripePaymentGateway('sk_test'))->authorize('k', Money::eur(100), 'pm');
}
}غلط: controller در نقش سرویس، مدل همراه facade
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
/**
* The fat "service" in controller form: validation, pricing policy, SQL into
* other contexts' tables, a payment call inside a DB transaction, and a
* hidden clock. Every rule is untestable without a database and Stripe.
*/
class OrderController
{
public function store(Request $request)
{
return DB::transaction(function () use ($request) {
$total = 0;
foreach ($request->input('items') as $item) {
$price = DB::table('catalog_products')->where('sku', $item['sku'])->value('price_minor');
$line = $price * $item['quantity'];
if ($item['sku'] === 'MUG' && $item['quantity'] >= 3) {
$line = intdiv($line * 90, 100); // pricing rule in a controller
}
$total += $line;
}
if ($request->user()->tier === 'gold') { // Identity's column read directly
$total = intdiv($total * 95, 100);
}
$total += $total < 5000 ? 495 : 0;
// network call while the transaction holds a connection and locks
$intent = Http::withToken(config('services.stripe.secret'))->asForm()
->post('https://api.stripe.com/v1/payment_intents', ['amount' => $total, 'currency' => 'eur'])
->json();
$order = Order::create([
'customer_id' => $request->user()->id,
'total_minor' => $total,
'payment_ref' => $intent['id'],
'placed_at' => now(), // hidden clock
]);
return response()->json($order, 201); // no event: Billing and Fulfilment never hear
});
}
}<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* Infrastructure leaking into the domain: a model whose "business method"
* reaches for static facades. It cannot run without a database, a cache and
* a mailer, so its rule cannot be unit-tested.
*/
class Order extends Model
{
protected $guarded = [];
public function applyLoyaltyDiscount(): void
{
$tier = Cache::remember("tier:{$this->customer_id}", 60, fn () => DB::table('identity_customers')->where('id', $this->customer_id)->value('tier'));
if ($tier === 'gold') {
$this->total_minor = intdiv($this->total_minor * 95, 100);
$this->save();
Mail::raw('You saved 5%!', fn ($m) => $m->to($this->customer_email));
}
}
}نگاه Laravel
- نگاشت. Form Request (لبه:
authorize()+rules()) ← command DTO ← use case یا کلاس Action (کاربرد) ← اشیای دامنه (PHP ساده) ← port مخزن ← adapter Eloquent ← outbox یا رویدادهایShouldDispatchAfterCommit. مدلهای Eloquent درInfrastructureبهعنوان رکورد ماندگاری زندگی میکنند. در ماژولی که CRUD ساده است، استفادهٔ مستقیم از Eloquent در use case انتخاب مشروعی است، ولی انتخابی است که آگاهانه میکنید (Anemic vs Rich). - container همان ریشهٔ ترکیب است. ویژگی
$bindingsportها را به adapterها نگاشت میکند.singletonاشیای پیکربندیشده میسازد.extenddecorator اضافه میکند. مستنداتextendرا راهی برای "decorate or configure the service" توصیف میکند. - jobها application service ناهمگاماند، یا دقیقتر، adapter رانندهٔ ناهمگام. job با
ShouldQueueباید یک command DTO حمل کند و همان use case را صدا بزند. نباید نسخهٔ دومی از جریان را در خودش داشته باشد. jobهایی را که دوباره اجرا میشوند idempotent کنید، و اگر داخل تراکنش ساخته میشوند با->afterCommit()dispatch کنید. - facade یک راحتی زیرساختی است.
DB::،Http::،Cache::،Mail::وnow()در adapter، controller و provider مشکلی ندارند. در کلاسهای دامنه وابستگیها را پنهان میکنند و قاعدهها را بدون فریمورک تستناپذیر میکنند.Date::now()درSystemClockباعث میشودtravelTo()در تست کار کند. Contextبرای correlation.Context::add('correlation_id', ...)در middleware شناسه را در هر خط لاگ و در jobهای صفی که در طول درخواست dispatch شدهاند میگذارد. بعد decoratorها بدون دستبهدست کردن شناسه لاگ مینویسند.- تراکنش.
DB::transaction(fn, attempts)(یاConnectionInterface::transaction) پشت portUnitOfWork، facade را از use case بیرون نگه میدارد. آرگومان دومش closure را "when a deadlock occurs" دوباره اجرا میکند.
حل مسئلههای کلاسیک
| مسئله | راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
| application service چاق | قاعدهها را پایین ببرید | هر if کسبوکاری متدی روی entity یا یک domain service میشود | قاعدهها unit-test پذیر و در همهٔ نقطههای ورود قابل استفادهاند | زمان بازآرایی؛ مدل غنی لازم است |
| domain service بهعنوان انباری | بر اساس عملیات بشکنید، قاعدهها را به entity برگردانید | یک سرویس برای هر عملیات نامدار؛ قاعدههای محلی برمیگردند | انسجام بیشتر، تستهای کوچکتر | برای نامگذاری دانش دامنه لازم است |
| «Service» روی همهچیز | با زبان فراگیر نام بگذارید | فعل برای use case، فناوری برای adapter | کد مثل کسبوکار خوانده میشود | تغییر نام به فایلهای زیادی دست میزند |
Eloquent / DB در دامنه | port مخزن + adapter | interface در دامنه، مدل Eloquent در Infrastructure | دامنه بدون دیتابیس اجرا میشود | کد نگاشت |
| facade ایستا در مدل | مقدار را ورودی بدهید یا port تزریق کنید | now بهعنوان آرگومان؛ port Clock در use case | تست قطعی | پارامترهای constructor بیشتر |
| فراخوانی بیرونی داخل تراکنش | بیرون صدا بزنید، جبران کنید | مجوز ← commit ← در شکست void؛ کلید idempotency | هیچ قفلی روی I/O شبکه نگه داشته نمیشود | منطق جبران؛ مسابقهٔ تکراری را باید مدیریت کرد |
| پخش رویداد پیش از commit | outbox یا پخش پس از commit | سطر outbox در همان tx؛ ShouldDispatchAfterCommit | رویداد شبح ساخته نمیشود | پردازهٔ relay؛ تحویل دستکم یکبار |
| همان جریان در controller و job و CLI کپی شده | یک use case، چند adapter راننده | controller، job و command همان DTO را میسازند | یک جا برای تغییر | نگاشت DTO برای هر adapter |
application service چاق
سرویس غلط Go و controller غلط چهار نوع کد را در یک تابع دارند: SQL روی دو جدول بیگانه، یک تخفیف سختکدشده، یک تخفیف وفاداری، یک فراخوانی Stripe داخل تراکنش، و ساعت دیواری. بازآرایی مکانیکی است:
- قاعدهها (
>= 3 mugs،gold،< 5000) را بهPricingServiceببرید و تست جدولی را اول بنویسید. رفتار امروز را قفل میکند. - SQL روی
catalog_productsوidentity_customersرا با portهایCatalogوCustomersعوض کنید. آنها را روی read modelهای محلی پیاده کنید، نه روی جدولهای ماژولهای دیگر (Data Ownership). - فراخوانی Stripe را از تراکنش بیرون ببرید و پشت
PaymentGatewayبگذارید، با کلید idempotency و void در شکست. time.Now()/now()را با portClockعوض کنید وnowرا به دامنه بدهید.OrderPlacedرا در aggregate ثبت کنید و در همان تراکنش به outbox اضافه کنید.
domain service بهعنوان انباری
نشانه: OrderDomainService با calculateTotal، canCancel، isEditable، formatForEmail، exportCsv. دربارهٔ هر متد بپرسید: به بیش از یک aggregate یا value object نیاز دارد؟ canCancel و isEditable فقط سفارش را لازم دارند، پس روی Order میروند. formatForEmail نمایش است و به adapter ایمیل میرود. exportCsv یک query handler است. فقط calculateTotal، که تخفیف و سطح را لازم دارد، با نام PricingService.Quote باقی میماند.
پسوند «Service» همهجا
بر اساس نقش نام بگذارید: use caseها به شکل فعل (PlaceOrder)، domain serviceها به نام مفهوم کسبوکار (PricingService، FundsTransfer)، adapterها به نام فناوری (StripePaymentGateway)، portها به نام توانایی (PaymentGateway، Clock). اگر نامی به ذهن نمیرسد، احتمالاً کلاس بیش از یک کار میکند.
نشت زیرساخت به دامنه از راه Eloquent یا DB
مدل Eloquent یک active record است: جدول و اتصالش را میشناسد. استفاده از آن بهعنوان شیء دامنه برای ماژولهای CRUD انتخاب معتبری است، ولی آن وقت دامنه بدون دیتابیس نه تست میشود و نه دربارهٔ آن میشود استدلال کرد. در ماژول اصلی، دامنه را PHP ساده نگه دارید. در EloquentOrderRepository آن را به OrderRecord و برعکس نگاشت کنید و UniqueConstraintViolationException را همانجا به DuplicateOrder دامنه تبدیل کنید. Repositories نگاشت را عمیق پوشش میدهد.
facade ایستا در لایهٔ دامنه
مدل غلط Order داخل applyLoyaltyDiscount() متدهای Cache::remember، DB::table و Mail::raw را صدا میزند. قاعده («طلایی ۵٪ میگیرد») سه خط است. بقیه زیرساخت است و همان سه خط را بدون cache و دیتابیس و mailer تستناپذیر میکند. درمان همان درمان سرویس چاق است: سطح مشتری بهعنوان آرگومان میآید، تخفیف در PricingService حساب میشود و ایمیل یک listener روی OrderPlaced میشود.
انتخاب: این منطق کجا برود؟
پانزده قاعده از کسبوکار سفارش، هر کدام در لایهٔ خودش:
| # | قاعده یا کد | جایش | نوع | دلیل |
|---|---|---|---|---|
| 1 | تعداد هر سطر سفارش بین 1 و 50 است | OrderLine / Order | Entity / value object | فقط دادهٔ خود سطر را لازم دارد |
| 2 | مبلغ = سطرها − تخفیفها − وفاداری + ارسال | PricingService.Quote | Domain service | سطرها، سطح و تخفیفها را با هم لازم دارد |
| 3 | فقط سفارش پیشنویس ثبت میشود | Order.Place | Aggregate | گذار state یک aggregate |
| 4 | انتقال 50 یورو از کیف A به کیف B با کارمزد | FundsTransfer | Domain service | مال هیچکدام از دو حساب نیست |
| 5 | سفارش را بار کن، ثبت کن، ذخیره کن، OrderPlaced را منتشر کن | PlaceOrderHandler | Application service | هماهنگسازی یک use case |
| 6 | Idempotency-Key تکراری نتیجهٔ اول را برمیگرداند | PlaceOrderHandler (کلید طبیعی) یا decorator | Application | دغدغهٔ پروتکل، نه قاعدهٔ کسبوکار |
| 7 | فقط مشتری واردشده با place-orders میتواند صدایش بزند | authorize() در Form Request / decorator | لبه | چه کسی اجازهٔ اجرای use case را دارد |
| 8 | items آرایهای غیرخالی از {sku, quantity} است | rules() در Form Request / decoder در HTTP | لبه | شکل، نه معنا |
| 9 | مجوز کارت با Stripe و capture_method=manual | StripePaymentGateway | Infrastructure service | فناوری پشت PaymentGateway |
| 10 | ساعت چند است؟ | adapter Clock | Infrastructure service | دامنه now را بهعنوان آرگومان میگیرد |
| 11 | نگاشت سطرهای sales_orders به Order | EloquentOrderRepository / postgres.Orders | زیرساخت (adapter مخزن) | جزئیات ماندگاری |
| 12 | پس از ثبت سفارش، ایمیل رسید بفرست | listener روی OrderPlaced + adapter Mailer | کاربرد (listener) + زیرساخت | واکنش به رویداد؛ ایمیل فنی است |
| 13 | هر command را با مدت و correlation id لاگ کن | LogsPlaceOrder / decorator.Logging | decorator سراسری | برای همهٔ use caseها یکی است |
| 14 | صفحهٔ «سفارشهای من»: 20 سفارش آخر با مبلغ | CustomerOrdersHandler + read model | Query handler | میخواند و چیزی را تغییر نمیدهد |
| 15 | برداشت پرداخت وقتی Fulfilment ارسال کرد | use case CapturePayment در Billing، روی ParcelDispatched | Application service در context دیگر | Billing صاحب پرداخت است؛ Sales فقط واکنش نشان میدهد |
کدام نوع سرویس؟ یک مسیر تصمیم کوتاه:
| پرسش | بله ← | نه ← |
|---|---|---|
| با دیتابیس، شبکه، فایل، ساعت یا منبع تصادف حرف میزند؟ | adapter زیرساخت پشت یک port | پرسش بعدی |
| قاعدهای کسبوکاری است که متخصص دامنه میشناسد؟ | پرسش بعدی | application service (هماهنگسازی) یا لبه (شکل، مجوز) |
| فقط دادهٔ یک entity یا value object را لازم دارد؟ | متدی روی همان entity / value object | Domain service |
| به چیزی که اتفاق افتاده واکنش نشان میدهد؟ | listener رویداد که یک use case را صدا میزند | use caseی که یک adapter راننده صدایش میزند |
در معماری: از یک پردازه تا سیستم توزیعشده
سه نوع سرویس با بزرگ شدن سیستم عوض نمیشوند. چیزی که عوض میشود این است که پشت هر port چه نشسته.
Monolith (یکپارچه): یک پردازه، یک دیتابیس
سادهترین نسخهٔ درست. یک monolith لاراولی یا Go با پوشههای Domain، Application، Infrastructure و یک دیتابیس. PlaceOrderHandler یک DB::transaction دارد. adapterهای Catalog و Customers میتوانند مستقیم جدول کاتالوگ و مشتری را بخوانند، چون یک تیم صاحب همهاش است. رویدادها میتوانند listenerهای درونپردازهای با ShouldDispatchAfterCommit باشند. مثال روزمره: یک فروشگاه کوچک که «ثبت سفارش» در همان درخواست ایمیل رسید میفرستد و از موجودی کم میکند.
نسخهٔ تولیدی همان monolith برای هر چیزی که از پردازه بیرون میرود (ایمیل، webhook به انبار) هنوز از outbox سود میبرد، چون listener درونپردازهای با مرگ پردازه از بین میرود.
Modular monolith و چند دیتابیس
Sales، Catalog، Identity، Fulfilment و Billing ماژولهایی با schema جدا میشوند (Modular Monolith). حالا port Catalog اهمیت پیدا میکند. Sales اجازه ندارد catalog_products را بخواند. یا sales_price_list را میخواند، که یک کپی محلی است و رویدادهای PriceChanged از Catalog پرش میکنند، یا interface منتشرشدهٔ PHP یا Go از Catalog را صدا میزند. application service عوض نمیشود؛ فقط adapter جابهجا شده. هر ماژول ریشهٔ ترکیب خودش را دارد (در لاراول یک service provider برای هر ماژول، در Go یک NewApplication() برای هر ماژول). مثال تولیدی: یک architecture test (Deptrac، arch() در Pest، go-arch-lint) وقتی Sales\Domain چیزی از Catalog\Infrastructure import کند build را میشکند.
Microservices (میکروسرویس): port به فراخوانی شبکه تبدیل میشود
وقتی Sales یک سرویس میشود (اینکه این خط کجا کشیده شود موضوع Service Boundaries است)، پیادهسازی سه port عوض میشود، نه شکلشان:
PaymentGateway. در فصلهای همسایه Billing صاحب پرداخت است. در این مقیاس Sales دیگر Stripe را صدا نمیزند. adapterPaymentGatewayیک client برای Billing میشود، یا قدم پرداخت کلاً ازPlaceOrderبیرون میرود. آن وقتPlaceOrderسفارشیpending_paymentذخیره میکند وOrderPlacedرا منتشر میکند، و Billing مجوز میگیرد و باPaymentAuthorizedیاPaymentFailedجواب میدهد. این یک saga است و void به یک قدم جبرانی تبدیل میشود.CatalogوCustomers. clientهای HTTP یا gRPC پشت لایهٔ ضدفساد، با timeout و circuit breaker (Service Communication)، یا replicaهای محلی که رویدادها پرشان میکنند.Outbox. بیتغییر، و حالا حیاتی. relay روی Kafka یا RabbitMQ منتشر میکند و مصرفکنندهها در Fulfilment و Billing با inbox تکراریها را حذف میکنند (Idempotent Consumers).
Service Use case / handler Talks through
1 Sales PlaceOrder: save pending, outbox -> broker: sales.order.placed.v1
2 Billing AuthorizePayment (on OrderPlaced) -> Stripe adapter; outbox: billing.payment_authorized
3 Sales ConfirmOrder (on PaymentAuthorized) aggregate: pending -> placed
4 Fulfilment ReserveStock (on OrderPlaced) outbox: fulfilment.stock_reserved
5 Sales CancelOrder (on PaymentFailed) outbox: sales.order.cancelled.v1 (compensation)مثال تولیدی: ساختار سیمکشی cmd/shop/main.go در Go تغییری نمیکند. payments یک billingclient.Gateway میشود و catalog یک client gRPC با مهلت ۳۰۰ میلیثانیه.
دادهٔ توزیعشده: replica، cache و چندمنطقهای
- query handlerها اول جابهجا میشوند.
CustomerOrdersHandlerاز replica یا projection میخواند. ممکن است کاربر تا اندازهٔ تأخیر replication سفارشش را نبیند. پس دادهٔ سفارش تازه را از نتیجهٔ command برگردانید، یا query بعدی همان کاربر را به primary بفرستید (Replication & Failover). - cache پشت portهای query مینشیند، هرگز جلوی command handlerها. باطلسازیاش را از روی رویدادها انجام بدهید.
- idempotency اجباری میشود. تلاش مجدد در هر گامی رخ میدهد: client، gateway، صف، relay. کلید طبیعی (
OrderIDازIdempotency-Key) بهعلاوهٔ یک قید unique ارزانترین تضمین است. Stripe کلیدها را دستکم ۲۴ ساعت نگه میدارد، پس کلید شما هم باید دستکم همینقدر پایدار بماند. - ساعتها میان nodeها همنظر نیستند. port
Clockرا برای زمان کسبوکار به کار ببرید، ولی هرگز برای ترتیبدادن رویدادها میان سرویسها. برای آن از شمارهٔ دنباله یا offset در broker استفاده کنید. - چندمنطقهای. هر منطقه سفارشهای خودش را مینویسد. قاعدههای قیمتگذاری (دامنه) کدند و همهجا deploy میشوند. فهرست قیمتها (داده) با رویداد replicate میشود.
مسیر مقیاس: ۱×، ۱۰×، ۱۰۰×
| بار | چه عوض میشود | چه عوض نمیشود |
|---|---|---|
| 1× (صدها سفارش در روز) | یک پردازه، رویداد درونپردازهای، یک دیتابیس | سه نوع سرویس و portها |
| 10× | outbox + relay، worker صف برای listenerهای کند، read replica برای queryها | کد use case؛ فقط adapterها و سیمکشی |
| 100× | Sales/Billing/Fulfilment بهشکل سرویس، saga بهجای پرداخت درونخطی، projection برای queryها، outbox بخشبندیشده | کد دامنه: Order، PricingService |
آزمایشگاه (Lab): ساختن، شکستن و ترمیم لایهها
بخش Go روی ماشین نویسنده اجرا شده. بخش Laravel expected, not run است (خروجی مورد انتظار، اجرا نشده).
۱. همهٔ تستهای Go را اجرا کنید (دامنه، کاربرد، adapter، قاعدهٔ وابستگی).
cd docs/snippets/ddd/domain-application-infrastructure-services/go
gofmt -l . && go vet ./... && go test ./...
# ok academy/domain-application-infrastructure-services/adapters/stripe
# ok academy/domain-application-infrastructure-services/app/command
# ok academy/domain-application-infrastructure-services/sales۲. سرویس را با adapterهای درونحافظه بالا بیاورید و یک سفارش ثبت کنید (مشتری طلایی، ۵ ماگ + ۲ چای).
ADDR=127.0.0.1:18089 go run ./cmd/shop &
curl -si -X POST localhost:18089/orders -H 'Idempotency-Key: o-1001' \
-d '{"customer_id":"c-gold","payment_token":"pm_card_visa","items":[{"sku":"MUG","quantity":5},{"sku":"TEA","quantity":2}]}'
# HTTP/1.1 201 Created
# {"order_id":"o-1001","total":"66.50 EUR"}۶۰ یورو ماگ − ۶ یورو تخفیف + ۱۶ یورو چای = ۷۰؛ منهای ۵٪ طلایی = ۶۶٫۵۰؛ از ۵۰ یورو به بالا ارسال رایگان است.
۳. همان درخواست را تکرار کنید: idempotency.
# same curl again
# HTTP/1.1 200 OK
# {"order_id":"o-1001","total":"66.50 EUR"}۴. یک قاعدهٔ دامنه را بشکنید و ببینید کدام لایه جواب میدهد.
curl -si -X POST localhost:18089/orders -H 'Idempotency-Key: o-1002' \
-d '{"customer_id":"c-1","items":[{"sku":"MUG","quantity":99}]}'
# HTTP/1.1 422 Unprocessable Entity
# quantity must be between 1 and 50
# server log: {"msg":"command handled","command":"PlaceOrder","ok":false} <- decorator, not the handler۵. قاعدهٔ وابستگی را بشکنید. به sales/pricing.go خط import _ "database/sql" را اضافه کنید و go test ./sales/ را اجرا کنید. خروجی مورد انتظار: pricing.go imports database/sql: the domain must not depend on it. بعد برش گردانید.
۶. Laravel (expected, not run). snippetهای PHP را در یک اپ Laravel 13 کپی کنید، SalesServiceProvider را در bootstrap/providers.php ثبت کنید، migration را اجرا کنید و بعد:
php artisan test --filter=PricingServiceTest # 3 passed (no app booted)
php artisan test --filter=PlaceOrderHandlerTest # 5 passed (fakes only)
php artisan test --filter=StripePaymentGatewayTest # 2 passed (Http::fake)بعد بلوک if ($tier === CustomerTier::Gold) را از PricingService به PlaceOrderHandler منتقل کنید. PricingServiceTest در حالت طلایی شکست میخورد، و این دقیقاً همان علامتی است که میگوید یک قاعده از دامنه بیرون رفته.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| «هر entity یک domain service لازم دارد.» | بیشتر قاعدهها روی entity و value object مینشینند؛ domain service برای عملیاتی است که روی چند تای آنها پخش است. |
| «application service منطق کسبوکار را نگه میدارد.» | فقط هماهنگ میکند. "It does not contain business rules or knowledge" (Fowler در خلاصهٔ Evans). |
| «domain service هر وقت داده خواست میتواند repository را صدا بزند.» | بهتر است use case داده را بار کند و بدهد؛ domain serviceی که I/O دارد دیگر خالص نیست و سختتر تست میشود. |
| «زیرساخت فقط دیتابیس است.» | ساعت، شناسه، ایمیل، پرداخت، فضای فایل، سرویسهای دیگر، feature flag: همه زیرساختاند. |
| «port و adapter یعنی برای هر کلاسی یک interface.» | port در مرز فناوری مینشیند. یک domain service خالص interface لازم ندارد. |
| «کل use case را، همراه فراخوانی پرداخت، در تراکنش بپیچید.» | I/O شبکه داخل تراکنش قفل نگه میدارد و ممکن است برای سفارشی rollback شده پول بگیرد. بیرون صدا بزنید و جبران کنید. |
| «پخش رویداد درست بعد از تغییر state اشکالی ندارد.» | فقط بعد از commit؛ وگرنه مصرفکنندهها روی دادهای کار میکنند که شاید rollback شود. |
| «اعتبارسنجی یکجا زندگی میکند.» | شکل در لبه، قاعده در دامنه؛ تکرار قاعده در لبه برای تجربهٔ کاربری بهتر اشکالی ندارد. |
| «facadeهای لاراول همیشه غلطاند.» | در adapter، controller و provider مشکلی ندارند؛ مشکل facade داخل کلاس دامنه است. |
| «CQS یعنی دو دیتابیس.» | CQS handlerها را جدا میکند؛ CQRS با read model جدا اختیاری است. |
| «job صف جای جداگانهای برای منطق کسبوکار است.» | job یک adapter راننده است: command را میسازد و همان use case را صدا میزند. |
| «clean، hexagonal و onion سه چیز متفاوتاند که باید یکی را انتخاب کرد.» | یک قاعدهٔ مشترک دارند (وابستگیها رو به داخل)؛ فرقشان در نقاشی و واژگان است. |
چکیده (Cheat sheet)
| موضوع | به خاطر بسپارید |
|---|---|
| Domain service | بیحالت، بدون I/O، نامگذاریشده با زبان فراگیر، روی چند شیء دامنه پخش |
| Application service | یک use case: بار کن، از راه دامنه تصمیم بگیر، ذخیره کن، منتشر کن؛ بدون قاعده |
| Infrastructure service | توانایی فنی پشت یک port؛ adapterها میتوانند از فریمورک استفاده کنند |
| قاعدهٔ وابستگی | کد منبع رو به داخل؛ دامنه چیزی رو به بیرون import نمیکند |
| Port | interfaceی که مال داخل است و با زبان آن نوشته شده |
| Adapter | پیادهسازی یک port با یک فناوری؛ راننده یا راندهشده |
| ریشهٔ ترکیب | main.go یا service provider؛ تنها جایی که نوعهای واقعی را میشناسد |
| تراکنش | مال application service؛ یک aggregate در هر تراکنش |
| فراخوانی بیرونی | بیرون از تراکنش، با کلید idempotency، در شکست جبران شود |
| رویدادها | aggregate ثبت میکند، همراهش ذخیره میشود (outbox) یا بعد از commit پخش میشود |
| command در برابر query | command handler از راه aggregate تغییر میدهد؛ query handler از view میخواند |
| سراسری | decorator و middleware: لاگ، متریک، مجوز، idempotency، تلاش مجدد |
| اعتبارسنجی | شکل در لبه (Form Request)، قاعده در دامنه |
| تست | دامنه: تست جدولی خالص؛ کاربرد: fake؛ adapter: contract / integration test |
| نامگذاری | فعل برای use case، مفهوم برای domain service، فناوری برای adapter |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا «محاسبهٔ مبلغ سفارش با تخفیف و سطح وفاداری» یک domain service است و نه متدی روی Order؟ حیاتی
پاسخ
پاسخ: چون دادهای لازم دارد که مال سفارش نیست: سطح مشتری (Identity) و تخفیفهای فعال. گذاشتنش روی Order سفارش را مجبور میکند دربارهٔ تخفیف و سطح چیز بداند. ولی هنوز قاعدهٔ دامنه است، پس در یک domain service بیحالت به نام PricingService مینشیند که همهٔ ورودیها را آرگومان میگیرد.
۲ — این خط را در یک application service میبینید: if ($tier === 'gold') $total = intdiv($total * 95, 100);. چه اشکالی دارد و کجا باید برود؟ حیاتی
پاسخ
پاسخ: یک قاعدهٔ کسبوکار (تخفیف وفاداری) در لایهٔ هماهنگسازی نشسته. تستهای دامنه آن را نمیسنجند و نقطههای ورود دیگر تکرارش خواهند کرد. جایش PricingService است (یا اگر فقط دادهٔ یک شیء را لازم داشت، یک value object).
۳ — چرا PlaceOrderHandler متد PaymentGateway.Authorize را پیش از باز کردن تراکنش صدا میزند و نه داخلش؟ مهم
پاسخ
پاسخ: فراخوانی شبکه داخل تراکنش یک اتصال و قفل سطرها را به اندازهٔ تأخیر فراهمکننده نگه میدارد، و اگر بعد commit شکست بخورد مجوزی دارید بیسفارش. صدا زدن بیرون از تراکنش و void در شکست، تراکنش را کوتاه و اثر جانبی را جبرانپذیر نگه میدارد.
۴ — دو درخواست یکسان با یک Idempotency-Key همزمان میرسند و هر دو از بررسی «وجود دارد؟» رد میشوند. چه اتفاقی میافتد و چرا بازنده نباید پرداخت را void کند؟ مهم
پاسخ
پاسخ: هر دو با کلید idempotency یکسان در Stripe مجوز میگیرند، پس یک PaymentIntent مشترک دارند. درج دوم با SQLSTATE 23505 شکست میخورد. void کردن مجوز برنده را لغو میکند. بازنده سفارش را دوباره میخواند و بهعنوان replay برمیگرداند.
۵ — port OrderRepository کجا اعلام شده و PaymentGateway کجا؟ چرا فرق دارند؟ حیاتی
پاسخ
پاسخ: OrderRepository در پکیج دامنه است، چون فقط از aggregateها حرف میزند. PaymentGateway، Clock و Outbox در لایهٔ کاربردند، چون فقط use caseها لازمشان دارند. در هر دو حالت interface مال داخل است و زیرساخت پیادهاش میکند.
۶ — در مثال لاراول دو adapter راننده و سه adapter راندهشده نام ببرید. مهم
پاسخ
پاسخ: راننده: PlaceOrderController همراه PlaceOrderRequest، و job PlaceOrderInBackground (تستها سومیاند). راندهشده: EloquentOrderRepository، StripePaymentGateway، SystemClock، DatabaseOutbox، DatabasePricingInputs.
۷ — در این فصل command handler و query handler چه فرقی دارند؟ حیاتی
پاسخ
پاسخ: command handler یک aggregate را بار میکند یا میسازد، در تراکنش اجرا میشود، رویداد میسازد و نتیجهای کمینه برمیگرداند. query handler مستقیم از جدول، view یا replica میخواند، aggregate بار نمیکند، رویداد نمیسازد و DTOهایی همشکل نیاز صدازننده برمیگرداند.
۸ — چرا ShouldDispatchAfterCommit جایگزین کامل outbox نیست؟ مهم
پاسخ
پاسخ: منتظر commit میماند، پس هیچوقت یک rollback را اعلام نمیکند. ولی رویداد فقط در حافظهٔ پردازه زندگی میکند: اگر پردازه میان commit و پخش بمیرد، رویداد گم میشود. سطر outbox همراه سفارش commit میشود و از crash جان سالم به در میبرد، و relay دستکم یکبار تحویلش میدهد.
۹ — Cache::remember(...) داخل متد کسبوکاری یک مدل Eloquent مشکل است؟ داخل یک adapter چطور؟ مهم
پاسخ
پاسخ: داخل متد کسبوکاری مدل، بله: یک وابستگی را پنهان میکند، قاعده را به یک cache در حال اجرا گره میزند و بدون فریمورک تستناپذیرش میکند. داخل adapter، نه: adapter همان جایی است که facadeهای فریمورک به آن تعلق دارند.
۱۰ — هر نوع سرویس را با چه ارزانترین روشی تست میکنید؟ حیاتی
پاسخ
پاسخ: Domain service: تست واحد جدولی خالص، بدون fake. Application service: fake درونحافظه برای هر port و سنجش اینکه چه ذخیره، منتشر، شارژ و void شد. adapter زیرساخت: contract یا integration test روی httptest/Http::fake() یا یک دیتابیس واقعی در CI.
۱۱ — وقتی Sales میکروسرویس میشود و Billing صاحب پرداخت است، چه بر سر port PaymentGateway میآید؟ مهم
پاسخ
پاسخ: یا adapterش یک client برای Billing میشود، یا قدم پرداخت از PlaceOrder بیرون میرود: Sales سفارشی در انتظار ذخیره میکند و OrderPlaced را منتشر میکند، Billing مجوز میگیرد و با یک رویداد جواب میدهد، و Sales تأیید یا لغو میکند. این یک saga است و void به یک قدم جبرانی تبدیل میشود.
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
| سرویس دامنه (Domain service) | عملیات بیحالت دامنه که روی چند entity/value object پخش است؛ بدون I/O؛ نامگذاریشده با زبان فراگیر |
| سرویس کاربردی (Application service) | شیئی که یک use case را با هماهنگکردن repositoryها، اشیای دامنه و portها اجرا میکند؛ قاعدهٔ کسبوکار ندارد |
| Use case / interactor | نام application service در Clean Architecture |
| Command handler | application service برای commandی که state را تغییر میدهد (واژگان CQS/CQRS) |
| Query handler | application serviceی که فقط میخواند و DTO برمیگرداند |
| سرویس زیرساخت (Infrastructure service) | توانایی فنی (پرداخت، ایمیل، ساعت، فضای فایل) که به شکل adapter پشت یک port پیاده شده |
| Service Layer | الگوی Fowler/Stafford در PoEAA: مرز برنامه که تراکنشها را کنترل میکند |
| Layered Architecture | الگوی Evans: جدا کردن دامنه از کد UI، کاربرد و زیرساخت |
| قاعدهٔ وابستگی (Dependency rule) | وابستگیهای کد منبع فقط رو به داخلاند (Martin) |
| وارونگی وابستگی (Dependency inversion) | هم سیاست سطح بالا و هم جزئیات سطح پایین به انتزاعهایی وابستهاند که مال سیاستاند |
| Port | interfaceی که مال داخل ششضلعی است؛ راننده (primary) یا راندهشده (secondary) |
| Adapter | پیادهسازی وابسته به فناوری یک port، یا صدازنندهٔ آن |
| معماری ششضلعی (Hexagonal) | port و adapter از Cockburn: یک داخل با portها، adapterهای بیرونی، بدون لایه |
| ریشهٔ ترکیب (Composition root) | تنها جایی که adapterهای واقعی ساخته و وصل میشوند |
| Service container | container تزریق وابستگی لاراول؛ type hintهای constructor را resolve میکند |
| Service provider | کلاس لاراول که bindingها را ثبت میکند؛ ریشهٔ ترکیب ماژول |
| Unit of work | تغییرهای یک تراکنش کسبوکاری را دنبال و اتمی commit میکند |
| تراکنش (Transaction) | واحد اتمی در سطح دیتابیس؛ مال application service |
| رویداد دامنه (Domain event) | چیزی که در دامنه اتفاق افتاده و aggregate ثبتش کرده |
| Outbox | جدولی که در همان تراکنش aggregate نوشته میشود؛ relay بعد از commit منتشرش میکند |
ShouldDispatchAfterCommit | interface لاراول: رویداد فقط بعد از commit تراکنش باز پخش شود |
afterCommit() | اصلاحگر dispatch job در لاراول: job فقط بعد از commit تراکنشهای باز push شود |
| DTO | شیء انتقال داده: ورودی (command/query) یا خروجی سادهٔ بیرفتار |
| Form Request | کلاس درخواست لاراول با authorize() و rules(): اعتبارسنجی و مجوز در لبه |
| Decorator | پوششی که همان interface را پیاده میکند و یک دغدغهٔ سراسری اضافه میکند |
| Middleware | decorator در سطح HTTP یا bus |
Context | facade لاراول که دادهاش به هر خط لاگ اضافه و با jobهای صف به اشتراک گذاشته میشود |
| کلید idempotency (Idempotency key) | کلیدی که client انتخاب میکند تا درخواست تکراری نتیجهٔ اول را برگرداند |
| جبران (Compensation) | کاری که اثری جانبی و rollbackناپذیر را از نظر معنایی خنثی میکند (void کردن مجوز) |
| CQS | جداسازی command و query: متد (یا handler) یا state را تغییر میدهد یا داده برمیگرداند |
| CQRS | مدلهای (و اغلب انبارههای) جدا برای نوشتن و خواندن |
| مدل دامنهٔ کمخون (Anemic domain model) | entityهایی با داده ولی بیرفتار؛ قاعدهها در سرویسها |
| Facade (لاراول) | proxy ایستا به یک سرویس container، مثل DB::، Cache::، Http:: |
| Contract test | تستی که میسنجد adapter به قرارداد سیمی سیستم بیرونی پایبند است |
| Fake | پیادهسازی کارکنندهٔ درونحافظه از یک port برای تست |
| لایهٔ ضدفساد (Anticorruption layer) | adapterی که مدل context دیگر را به مدل ما ترجمه میکند |
| Wild Workouts | پروژهٔ نمونهٔ Go از Three Dots Labs برای DDD، CQRS و clean architecture |
منابع (References)
- Eric Evans, Domain-Driven Design Reference (2015), "Services" and "Layered Architecture": https://www.domainlanguage.com/wp-content/uploads/2016/05/DDD_Reference_2015-03.pdf
- Martin Fowler (Randy Stafford), Service Layer, PoEAA catalogue: https://martinfowler.com/eaaCatalog/serviceLayer.html
- Martin Fowler, AnemicDomainModel (2003): https://martinfowler.com/bliki/AnemicDomainModel.html
- Martin Fowler, CommandQuerySeparation (2005): https://martinfowler.com/bliki/CommandQuerySeparation.html
- Alistair Cockburn, Hexagonal Architecture (2005): https://alistair.cockburn.us/hexagonal-architecture/
- Robert C. Martin, The Clean Architecture (2012): https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html
- Miłosz Smółka, Introducing Clean Architecture by refactoring a Go project (2020): https://threedots.tech/post/introducing-clean-architecture/
- Robert Laszczak, How to use basic CQRS in Go (2020): https://threedots.tech/post/basic-cqrs-in-go/
- Three Dots Labs, Repository pattern in Go: https://threedots.tech/post/repository-pattern-in-go/
- Wild Workouts example repository: https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example
- Chris Richardson, Transactional outbox: https://microservices.io/patterns/data/transactional-outbox.html
- Stripe API, Idempotent requests: https://docs.stripe.com/api/idempotent_requests
- Laravel 13: Service Container https://laravel.com/docs/13.x/container · Service Providers https://laravel.com/docs/13.x/providers · Validation (Form Requests) https://laravel.com/docs/13.x/validation · Queues https://laravel.com/docs/13.x/queues · Events https://laravel.com/docs/13.x/events · Context https://laravel.com/docs/13.x/context · Database https://laravel.com/docs/13.x/database · HTTP Client https://laravel.com/docs/13.x/http-client
- Laravel Actions (lorisleiva): https://github.com/lorisleiva/laravel-actions
- Jeffrey Palermo, The Onion Architecture: part 1 (2008): https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/
- Go Code Review Comments, "Interfaces": https://go.dev/wiki/CodeReviewComments
- دریافت نشده و فقط برای جهتیابی ارجاع داده شده: Vaughn Vernon, Implementing Domain-Driven Design (2013), ch. 7 "Services", ch. 14 "Application"؛ Vlad Khononov, Learning Domain-Driven Design (O'Reilly, 2021).