11 · 實戰架構模式
DDD 與整潔架構實戰
當你套核心業務規則要比眼前用緊嘅 SQL driver、電郵供應商或者 HTTP 框架更加長命嗰陣,行 DDD / 整潔架構(六角形架構) 就可以將所有外部基建雜務隔絕喺核心模型之外。喺 dn-ioc 入面做依賴倒置,完全唔使寫抽象 base class 或者複雜嘅 Container Module:最入面嘅 domain/ 負責宣告介面同 token() port,application/ 用 provide() 編排 Use Case,而最出面嘅 infra/ 將真實 adapter 打包成單一個 bundleProviders() 匯出就搞掂。
1src/2├── domain/ # 唔准 import 專案入面任何其他層3│ ├── order.ts # Order 實體 + OrderRepository port 介面與 token4│ └── ports.ts # Clock、Mailer 等橫切 port 介面與 token5├── application/ # 只准 import domain/6│ ├── order-service.ts # OrderService 用例 Ref,inject domain 層嘅 token7│ └── order-service.test.ts # 純記憶體單元測試:綁定輕量假實作8├── infra/ # 只准 import domain/9│ ├── sql-order-repository.ts # 內部私有 sqlTableRef + sqlOrderRepositoryProvider10│ ├── system-adapters.ts # systemClockProvider + smtpMailerProvider11│ └── providers.ts # infraProviders = bundleProviders(...)12└── main.ts # Composition Root:唯一同時 import application/ 同 infra/ 嘅地方
1. 純淨嘅領域實體與 Port Token(domain/)
domain/ 資料夾坐鎮成張依賴圖嘅正中心,絕對唔會 import 專案入面任何其他分層。除咗 Order 呢類領域實體之外,佢仲會定義外部世界必須配合嘅 Port(端口)——既包括持久化儲存(OrderRepository),亦包括系統時間(Clock)同發送電郵(Mailer)呢類橫切副作用。
每個 Port 都係一對拍檔:一個 TypeScript interface,配一個直接跟介面改名嘅 token<T>('Name')。將讀取時間收埋喺 clockToken 後面,業務邏輯入面就唔使周圍直接 call new Date(),凡係同時間有關嘅狀態轉換喺測試入面都可以做到 100% 穩定可控。
- domain/
1import { token } from 'dn-ioc'23export interface Order {4 id: string5 customerEmail: string6 status: 'draft' | 'submitted'7 submittedAt?: Date8}910export interface OrderRepository {11 find(id: string): Promise<Order | undefined>12 save(order: Order): Promise<void>13}1415export const orderRepositoryToken = token<OrderRepository>('OrderRepository')
1import { token } from 'dn-ioc'23export interface Clock {4 now(): Date5}67export interface Mailer {8 sendOrderConfirmation(email: string, orderId: string): Promise<void>9}1011export const clockToken = token<Clock>('Clock')12export const mailerToken = token<Mailer>('Mailer')
2. 應用層 Use Case(application/)
application/ 層負責協調領域實體同各個 Port,去完成好似 OrderService.submit(id) 咁嘅業務流程。留意呢度特登採用咗一種好實用嘅混合寫法:
OrderService攞外部能力嗰陣,清一色透過 domain token(orderRepositoryToken、clockToken、mailerToken)注入——佢完全唔知亦唔理啲訂單到底擺喺 Postgres、SQLite 定係記憶體Map入面。- 但係
orderServiceRef自己本身,就係用provide(({ inject }) => { ... })匯出成一個Ref!點解呢?因為會去呼叫application/嘅人——無論係 HTTP Controller、CLI 指令、Queue Worker 定係測試——全部都住喺更外層,本來就應該直接向內import業務 Use Case。既然 import 箭嘴方向已經指緊向內,就完全冇必要畫蛇添足再整多個多餘 Token。
1import { provide } from 'dn-ioc'2import { type Order, orderRepositoryToken } from '../domain/order'3import { clockToken, mailerToken } from '../domain/ports'45export const orderServiceRef = provide(({ inject }) => {6 const orders = inject(orderRepositoryToken)7 const clock = inject(clockToken)8 const mailer = inject(mailerToken)910 return {11 async submit(id: string): Promise<Order> {12 const order = await orders.find(id)13 if (!order) {14 throw new Error(`Order ${id} not found`)15 }16 if (order.status === 'submitted') {17 throw new Error(`Order ${id} already submitted`)18 }1920 const submitted: Order = {21 ...order,22 status: 'submitted',23 submittedAt: clock.now(),24 }2526 await orders.save(submitted)27 await mailer.sendOrderConfirmation(submitted.customerEmail, submitted.id)28 return submitted29 },30 }31})
3. 基礎設施 Adapter 與打包(infra/)
infra/ 資料夾負責 import domain/ 嘅契約,並對住真實嘅 DB driver、第三方 SDK 同資料庫寫出具體實作:
- 將底層 Driver Handle 鎖死喺
infra/內部: 喺sql-order-repository.ts入面,sqlTableRef係一個唔對外公開嘅內部Ref,負責揸住底層資料表/連線池狀態兼登記onDispose清理 hook。sqlOrderRepositoryProvider喺幕後自動注入sqlTableRef,而domain/同application/由頭到尾都唔知道有sqlTableRef嘅存在。 - 將成層基建打包成
infraProviders:infra/providers.ts將sqlTableRef(確保 root scope 入面所有 adapter 共用同一個底層 client)連同所有provideFor()綁定,一次過收進單一個bundleProviders(...)handle。 - 新增 Adapter 只需改兩處: 之後每次要加新嘅基建 adapter,淨係喺
infra/入面做兩步——寫好佢個provideFor()綁定,再加一行落infraProviders。出面所有程式入口檔案連一行都唔使郁。
- infra/
1import { provide, provideFor } from 'dn-ioc'2import { type Order, orderRepositoryToken } from '../domain/order'34// Private infrastructure client — never imported by domain or application5export const sqlTableRef = provide(({ onDispose }) => {6 const rows = new Map<string, Order>([['ord-1', { id: 'ord-1', customerEmail: 'ada@example.com', status: 'draft' }]])7 onDispose(() => {8 rows.clear()9 })10 return rows11})1213export const sqlOrderRepositoryProvider = provideFor(orderRepositoryToken, ({ inject }) => {14 const rows = inject(sqlTableRef)15 return {16 find: async id => rows.get(id),17 save: async order => {18 rows.set(order.id, order)19 },20 }21})
1import { provideFor } from 'dn-ioc'2import { clockToken, type Mailer, mailerToken } from '../domain/ports'34const smtpMailer: Mailer = {5 async sendOrderConfirmation(email, orderId) {6 // Stands in for an SMTP or transactional email HTTP client7 void email8 void orderId9 },10}1112export const systemClockProvider = provideFor(clockToken, () => ({ now: () => new Date() }))13export const smtpMailerProvider = provideFor(mailerToken, () => smtpMailer)
1import { bundleProviders } from 'dn-ioc'2import { sqlOrderRepositoryProvider, sqlTableRef } from './sql-order-repository'3import { smtpMailerProvider, systemClockProvider } from './system-adapters'45// One bundle collects every infrastructure adapter; entrypoints install it once6export const infraProviders = bundleProviders(7 sqlTableRef,8 sqlOrderRepositoryProvider,9 systemClockProvider,10 smtpMailerProvider,11)
4. Composition Root 與多入口重用
main.ts 就係成個專案嘅 Composition Root(組裝根)——全個 repo 唯一同時 import application/ 同 infra/,並透過 providers: [infraProviders] 將兩邊扣埋一齊嘅地方。
正因為 infraProviders 係一個可以隨處重用嘅打包值,而 orderServiceRef 又同傳輸層完全解耦,想喺同一套領域模型上面開多幾個唔同入口,每個都係幾行 code 就搞掂:
- HTTP API 伺服器(
main.ts): 掛上[infraProviders],喺bootstrapApp()入面即場inject(orderServiceRef)(萬一漏綁咗任何一個 Token,一跑await app.start()就會即刻爆錯,唔會等到真實客落單行到一半先出事),然後交畀路由層處理請求。 - 背景 Queue Worker 或 CLI 腳本(
worker.ts): 喺獨立入口檔案 callbootstrapApp(..., { providers: [infraProviders] }),照樣注入同一個orderServiceRef——如果係跑緊補資料腳本唔想真係發電郵騷擾客,仲可以喺infraProviders後面 補多句provideFor(mailerToken, dryRunMailer)即場蓋走電郵服務。 - 純單元測試(
application/order-service.test.ts): 完全唔載入infraProviders,淨係綁幾個超輕量嘅記憶體provideFor()假實作。就算漏綁咗一個 Port,unitTestApp.start()都會即刻 rejectNo provider for token: Mailer。
- application/
1import { bootstrapApp } from 'dn-ioc'2import { orderServiceRef } from './application/order-service'3import { infraProviders } from './infra/providers'45// Composition Root: the only module that imports both application and infra6export const app = bootstrapApp(7 async ({ inject }) => {8 const orders = inject(orderServiceRef)9 const submitted = await orders.submit('ord-1')10 console.log(submitted.status) // submitted11 },12 {13 providers: [infraProviders],14 },15)1617await app.start()18await app.stop()
1import { bootstrapApp, provideFor } from 'dn-ioc'2import { orderServiceRef } from './application/order-service'3import { type Order, type OrderRepository, orderRepositoryToken } from './domain/order'4import { clockToken, type Mailer, mailerToken } from './domain/ports'56const saved: Order[] = []7const sentEmails: string[] = []8const fixedNow = new Date('2026-11-18T12:00:00.000Z')910const fakeOrderRepository = (): OrderRepository => ({11 find: async id => ({ id, customerEmail: 'ada@example.com', status: 'draft' }),12 save: async order => {13 saved.push(order)14 },15})1617const fakeMailer = (): Mailer => ({18 sendOrderConfirmation: async (email, orderId) => {19 sentEmails.push(`${email}:${orderId}`)20 },21})2223export const unitTestApp = bootstrapApp(24 async ({ inject }) => {25 const result = await inject(orderServiceRef).submit('ord-42')26 console.log(result.status, saved.length, sentEmails) // submitted 1 [ 'ada@example.com:ord-42' ]27 },28 {29 // Pure fakes only — forgetting any token fails fast with "No provider for token: <Name>"30 providers: [31 provideFor(orderRepositoryToken, fakeOrderRepository),32 provideFor(clockToken, () => ({ now: () => fixedNow })),33 provideFor(mailerToken, fakeMailer),34 ],35 },36)3738await unitTestApp.start()39await unitTestApp.stop()
5. 分層 Import 邊界速查
由於 dn-ioc 喺 runtime 只處理 handle,唔會干預靜態 import 語句,日常開發記實下面張分層依賴方向表就夠:
| 分層目錄 | 准許引入嘅專案路徑 | 嚴禁引入嘅專案路徑 |
|---|---|---|
domain/ | 冇(只准引入 'dn-ioc' 嘅 token) | application/、infra/、main.ts |
application/ | domain/ | infra/、main.ts |
infra/ | domain/ | application/、main.ts |
main.ts(各個入口檔) | application/、infra/、domain/ | — |
睇完兩種專案架構之後,下一篇我哋將單元測試同整合測試擺埋一齊對比——即刻揭去測試與替身模擬。