Community编程与开发github.com

mianhtsys/landingMod3

实现经过验证的后端架构模式,包括整洁架构(Clean Architecture)、六边形架构(Hexagonal Architecture)和领域驱动设计(Domain-Driven Design)。在设计新微服务的整洁架构、重构单体以使用限界上下文、实现六边形或洋葱架构模式、或调试应用层之间的依赖循环时,请使用此技能。

landingMod3 是什么?

此技能专注于教授和引导开发者应用三种主流的后端架构模式:整洁架构、六边形架构和领域驱动设计。其核心目标在于构建可维护、可测试且可扩展的系统。技能明确指出,在依赖注入原则下,业务逻辑应独立于框架和数据库,每一层边界通过抽象接口进行交互。它支持在从零开始设计新服务、拆分单体应用、或调试基础设施代码侵入领域层等场景下使用。技能详细解释了各模式的层结构(如整洁架构的四层)、关键组件(如六边形架构中的端口与适配器)以及DDD的战术模式(如聚合、值对象、领域事件),并提供了使用内存适配器进行纯粹单元测试的代码示例,以验证架构的正确应用。该技能适用于Claude Code、Cursor、Codex等支持自定义指令的AI编程助手,用户通过引用该技能可让AI助手遵循这些架构原则生成代码。

兼容平台~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 的新对话。

文档

架构模式

掌握经过验证的后端架构模式,包括整洁架构(Clean Architecture)、六边形架构(Hexagonal Architecture)和领域驱动设计(Domain-Driven Design),以构建可维护、可测试且可扩展的系统。

给定: 一个服务边界或模块需要架构设计。 产出: 具有清晰依赖规则、接口定义和测试边界的层次化结构。

何时使用此技能

  • 从头开始设计新的后端服务或微服务
  • 重构单体应用,其中业务逻辑与ORM模型或HTTP关注点纠缠在一起
  • 在将系统拆分为多个服务之前,建立限界上下文
  • 调试依赖循环,即基础设施代码渗入领域层
  • 创建可测试的代码库,使用例测试无需运行数据库
  • 实现领域驱动设计的战术模式(聚合、值对象、领域事件)

核心概念

1. 整洁架构(Bob大叔)

层(依赖方向向内):

  • 实体(Entities): 核心业务模型,不导入框架
  • 用例(Use Cases): 应用业务规则,编排实体
  • 接口适配器(Interface Adapters): 控制器、展示器、网关——在用例与外部格式之间进行转换
  • 框架与驱动程序(Frameworks & Drivers): UI、数据库、外部服务——全部位于最外层

关键原则:

  • 依赖方向向内;内层对外层一无所知
  • 业务逻辑独立于框架、数据库和交付机制
  • 每一层边界通过抽象接口跨越
  • 可测试,无需UI、数据库或外部服务

2. 六边形架构(端口与适配器)

组件:

  • 领域核心(Domain Core): 业务逻辑在此,无框架依赖
  • 端口(Ports): 定义核心与外部世界如何交互的抽象接口(驱动端和被驱动端)
  • 适配器(Adapters): 端口的具体实现(PostgreSQL适配器、Stripe适配器、REST适配器)

优点:

  • 无需触及核心即可切换实现(例如,将PostgreSQL替换为DynamoDB)
  • 在测试中使用内存适配器——无需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.

相关技能