Three-Tier Architecture
當你在瀏覽網頁時,其實是在跟三個不同層次組成的系統進行互動。
這個系統就是 Web 的三層式架構:
- Presentation Layer (View, Middleware, Controller, …)
- Application Layer (Service, Domain Model, …)
- Data Access Layer (Repository, Proxy, Dal, …)
由於在討論這些架構時,大家使用的名稱常略有不同,下面列出其職責。
Controller
職責:
- Routing 解析 (Http, gRPC, …)
- 驗證 Request (確保格式、權限等是正確的)
- 將 Request 轉成 DTO,交給 Service 處理
- 依據 Service 回傳的 Domain Model,準備 Response
- Exception 處理
- Cache 管理
Middleware
職責:
- Global Exception Handler
- Log Handler
- Validator
Service
職責:
- Transaction 處理 (begin, commit, rollback)
- 調用 Domain Model (包含從 Repository 取得、自己 Construct 等)
- 讓 Domain Model 彼此去互動
- 資料驗證 (確保其合法性、完整性等)
Repository
職責:
- 處理 DB Connection
- 處理外部 API 呼叫 (Signature, Url, …)
- 從資料來源檢索並轉換成 Domain Model
- input 會以 Domain Model、Dto 為主
- output 會以 Domain Model 為主
- 命名參照 Domain Model,跟 table name 只是剛好撞名
- 內含數個 Dal、Proxy,呼叫後將各個結果組合成 Domain Model
Dal / Proxy
職責:
- Dal 命名通常 1-1 mapping table,處理與 DB 的互動,
但要留意效能問題,適時使用 join 語法調校 (ex: UserDal) - Proxy 處理 api 的 request/response,回傳原始值給 Repository
補充
Simple Design
- Pass all tests
- Reveals intention
- No duplication
- Fewest elements
ʕ •ᴥ•ʔ:這是目前與 Erwin 討論及請教 91 後的理解,
未來有可能因開發經驗的增加或團隊組成而再發生改變。
[2024-08-30] 更新
跟 James 討論後,新增了 Client 架構,角色類似於 Dal。
跟 Kyo 討論時,有提到使用 Dal 的效能問題。
[2026-01-09] 更新
跟 Erwin 及部門討論後,將 Dal 改名成 Dal,並將 Client & Proxy 合併列入 Dal 層級。