Community程式設計與開發github.com

mianhtsys/landingMod3

實作經過驗證的後端架構模式,包括乾淨架構、六角形架構與領域驅動設計。在設計新的微服務、將單體重構為有限脈絡、實作六角形或洋蔥架構,或除錯應用層之間的依賴循環時,可使用此技能。

landingMod3 是什麼?

此技能專門為開發者與 AI 代理提供實作 Clean Architecture、Hexagonal Architecture 與 Domain-Driven Design (DDD) 等經過驗證的後端架構模式之方法。其主要用途在於設計新的微服務或模組時,建立具有明確依賴規則、介面定義與測試邊界的分層結構。技能包含詳細的核心概念說明,例如獨立的領域實體、僅向內相依的用例層、透過 Port 與 Adapter 隔離基礎設施,以及 DDD 的策略模式(如 Bounded Context)與戰術模式(如 Aggregate、Value Object)。此外,技能提供具體的程式碼範例,展示如何透過記憶體 Adapter 進行無需資料庫的純單元測試,並針對常見的架構問題(如循環導入、控制器過於臃腫)提供解決方案。支援平台包括使用 Python 語言的後端專案,但這些模式本身語言無關。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mianhtsys/landingMod3/tree/HEAD/MODULO_3_DESARROLLO_AL_LADO_DEL_CLIENTE_Y_SERVIDOR_WEB/architecture-skills-framework/.agents/skills/architecture-patterns

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

架構模式

精通經過驗證的後端架構模式,包括乾淨架構、六角形架構與領域驅動設計,以建構可維護、可測試且可擴展的系統。

給定: 一個服務邊界或待設計的模組。 產出: 帶有清晰依賴規則、介面定義與測試邊界的分層結構。

何時使用此技能

  • 從頭設計新的後端服務或微服務
  • 重構單體應用程式,當業務邏輯與 ORM 模型或 HTTP 關注點糾纏不清時
  • 在將系統拆分為服務之前,建立有限的脈絡(Bounded Context)
  • 除錯基礎設施程式碼滲入領域層的依賴循環
  • 建立可測試的程式庫,讓用例測試無需執行中的資料庫
  • 實作領域驅動設計的戰術模式(聚合、值物件、領域事件)

核心概念

1. 乾淨架構(Uncle Bob)

層級(依賴向內流動):

  • 實體(Entities):核心業務模型,無框架匯入
  • 用例(Use Cases):應用程式業務規則,協調實體
  • 介面適配器(Interface Adapters):控制器、呈現器、閘道 —— 在用例與外部格式之間轉換
  • 框架與驅動(Frameworks & Drivers):UI、資料庫、外部服務 —— 皆在最外圈

關鍵原則:

  • 依賴僅指向內圈;內層對外層一無所知
  • 業務邏輯獨立於框架、資料庫與傳遞機制
  • 每個層級邊界均透過抽象介面跨越
  • 可在無 UI、資料庫或外部服務的情況下進行測試

2. 六角形架構(Ports and Adapters)

元件:

  • 領域核心(Domain Core):業務邏輯在此,無框架
  • 埠(Ports):定義核心如何與外部世界互動的抽象介面(驅動與被驅動)
  • 適配器(Adapters):埠的具體實作(PostgreSQL 適配器、Stripe 適配器、REST 適配器)

優點:

  • 無需觸及核心即可更換實作(例如以 DynamoDB 取代 PostgreSQL)
  • 在測試中使用記憶體適配器——無需 Docker
  • 技術決策延至邊緣

3. 領域驅動設計(DDD)

策略模式:

  • 有限脈絡(Bounded Contexts):為一個子領域隔離一致的模型;避免在整個系統中共享單一模型
  • 脈絡映射(Context Mapping):定義脈絡之間的關係(防腐層、共享核心、開放主機服務)
  • 通用語言(Ubiquitous Language):程式碼中的每個術語都與領域專家使用的術語一致

戰術模式:

  • 實體(Entities):具有穩定身份且隨時間變化的物件
  • 值物件(Value Objects):由其屬性識別的不可變物件(Email、Money、Address)
  • 聚合(Aggregates):一致性邊界;僅能從外部存取根
  • 儲存庫(Repositories):持久化並重建聚合;抽象化儲存機制
  • 領域事件(Domain Events):捕捉領域內發生的事件;用於跨聚合協調

詳細模式與實作範例

詳細模式文件位於 references/details.md。當上述導航層級不足時,請閱讀該文件。

測試 —— 記憶體適配器

正確應用乾淨架構的標誌是,每個用例都可以在純單元測試中執行,無需真實資料庫、無需 Docker、無需網路:

# tests/unit/test_create_user.py
import asyncio
from typing import Dict, Optional
from domain.entities.user import User
from domain.interfaces.user_repository import IUserRepository
from use_cases.create_user import CreateUserUseCase, CreateUserRequest


class InMemoryUserRepository(IUserRepository):
    def __init__(self):
        self._store: Dict[str, User] = {}

    async def find_by_id(self, user_id: str) -> Optional[User]:
        return self._store.get(user_id)

    async def find_by_email(self, email: str) -> Optional[User]:
        return next((u for u in self._store.values() if u.email == email), None)

    async def save(self, user: User) -> User:
        self._store[user.id] = user
        return user

    async def delete(self, user_id: str) -> bool:
        return self._store.pop(user_id, None) is not None


async def test_create_user_succeeds():
    repo = InMemoryUserRepository()
    use_case = CreateUserUseCase(user_repository=repo)

    response = await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice"))

    assert response.success
    assert response.user.email == "[email protected]"
    assert response.user.id is not None


async def test_duplicate_email_rejected():
    repo = InMemoryUserRepository()
    use_case = CreateUserUseCase(user_repository=repo)

    await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice"))
    response = await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice2"))

    assert not response.success
    assert "already exists" in response.error

故障排除

用例測試需要執行中的資料庫

業務邏輯已洩漏至基礎設施層。將所有資料庫呼叫移至 IRepository 介面之後,並在測試中注入記憶體實作(請參閱上方測試章節)。用例建構子必須接受抽象的埠,而非具體類別。

層級之間的循環匯入

常見症狀是 use_cases 與 adapters 之間出現 ImportError: cannot import name X。這通常發生在用例匯入了具體的適配器類別而非抽象的埠時。請強制執行規則:use_cases/ 僅從 domain/(實體與介面)匯入,絕不能從 adapters/ 或 infrastructure/ 匯入。

領域實體中出現框架裝飾器

如果 SQLAlchemy 的 Column() 或 Pydantic 的 Field() 註解出現在領域實體上,則該實體就不再純淨。請在 adapters/repositories/ 中建立一個獨立的 ORM 模型,並在儲存庫的 _to_entity() 方法中與領域實體進行對應轉換。

所有邏輯最終都集中在控制器中

當控制器成長到超出 HTTP 解析與回應格式化的範疇時,請將邏輯提取到用例類別中。一個控制器方法應僅做三件事:解析請求、呼叫用例、映射回應。

值物件太晚拋出錯誤

在 __post_init__(Python)或建構子中驗證不變量,確保無法構造無效的 Email 或 Money。這能讓錯誤資料在邊界處就被發現,而非深藏在業務邏輯內部。

跨有限脈絡的脈絡洩漏

如果 Order 脈絡正從 Identity 脈絡匯入 User 實體,請引入一個防腐層。Order 脈絡應持有自己的輕量 CustomerId 值物件,並僅透過明確的介面來呼叫 Identity 脈絡。

進階模式

有關詳細的 DDD 有限脈絡映射、完整多服務專案樹、防腐層實作與洋蔥架構比較,請參閱:

相關技能

  • microservices-patterns —— 在將單體分解為服務時應用這些架構模式
  • cqrs-implementation —— 使用乾淨架構作為 CQRS 命令/查詢分離的結構基礎
  • saga-orchestration —— Saga 需要定義良好的聚合邊界,而 DDD 戰術模式正好提供此功能
  • event-store-design —— 由聚合產生的領域事件可直接饋入事件儲存

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mianhtsys/landingMod3

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

mianhtsys/landingMod3

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

mianhtsys/landingMod3

Diseña y compara alternativas arquitectónicas trazables a RF/RNF sin implementar código.

mianhtsys/landingMod3

Revisión adversarial de la arquitectura contra RF/RNF, detectando contradicciones, cobertura faltante y complejidad innecesaria.

mianhtsys/landingMod3

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

mianhtsys/landingMod3

>- Generate grounded-and-verified, engine-agnostic database documentation that reaches 100% parity with the real schema. Introspects the LIVE database as ground truth and cross-validates it against ORM models, migrations, generated types, seeds, and application queries, then proves completeness by diffing the docs back against the database. Produces ER diagrams (mermaid), per-table data dictionaries, and a machine-readable schema.json. Works with PostgreSQL, MySQL, SQL Server, and SQLite across any ORM (Prisma, TypeORM, Drizzle, Sequelize, Knex, Django, Rails) or raw SQL. Use when asked to document a database, produce an ERD or data dictionary, write db/schema docs, audit schema drift, or refresh existing DB docs.

mianhtsys/landingMod3

Compara estrategias de persistencia y motores de datos según consistencia, concurrencia, volumen, recuperación y operación.

mianhtsys/landingMod3

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

mianhtsys/landingMod3

Consolida análisis especializados en una recomendación arquitectónica, matriz de decisión, ADR y plan de validación.

mianhtsys/landingMod3

Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.

mianhtsys/landingMod3

Build and maintain web frontends — component architecture, state management, API integration, responsive layout, client-side performance, and frontend testing patterns. Framework agnostic, focused on web frontend implementation. Do not use for backend service implementation, data engineering, or platform infrastructure work.

mianhtsys/landingMod3

Evalúa despliegue, contenedores, escalado, alta disponibilidad, observabilidad, backup, recuperación y CI/CD de forma proporcional.

mianhtsys/landingMod3

Execute read-only SQL queries against multiple Microsoft SQL Server databases. Use when: (1) querying MSSQL/SQL Server databases, (2) exploring database schemas/tables, (3) running SELECT queries for data analysis, (4) checking database contents. Supports multiple database connections with descriptions for intelligent auto-selection. Blocks all write operations (INSERT, UPDATE, DELETE, DROP, etc.) for safety.

mianhtsys/landingMod3

Generate and maintain OpenAPI 3.1 specifications from code, design-first specs, and validation patterns. Use when creating API documentation, generating SDKs, or ensuring API contract compliance.

mianhtsys/landingMod3

PHP 8.0+ development — XAMPP, RESTful APIs, PDO/MySQL/MariaDB, and authentication. Use when building PHP backends, creating API endpoints, configuring XAMPP, or integrating PHP with databases.

mianhtsys/landingMod3

Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features

mianhtsys/landingMod3

Analiza requisitos funcionales y no funcionales, reglas, restricciones, capacidad y ambigüedades antes de seleccionar tecnologías.

mianhtsys/landingMod3

Implement modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first breakpoint strategies. Use when building adaptive interfaces, implementing fluid layouts, or creating component-level responsive behavior.

mianhtsys/landingMod3

>- Use when designing or implementing software securely: define security requirements, threat-model a feature, choose secure defaults, design authentication and authorization, handle untrusted data and secrets, evaluate dependencies, design multi-tenant trust boundaries, or review security-sensitive changes. Use for prevention during requirements, design, implementation, and review; not for post-build security assessments or scanning an existing codebase.

mianhtsys/landingMod3

Revisa seguridad arquitectónica, identidad, autorización, secretos, APIs, auditoría, fraude y resiliencia antes de implementar.

相關技能