Hexagonal architecture

From aaione/everything-claude-code-zh · View interactive version

Hexagonal architecture is an AI agent skill from the GitHub repository aaione/everything-claude-code-zh. 设计、实现和重构端口与适配器系统,具有清晰的域边界、依赖倒置和可测试用例编排,跨 TypeScript、Java、Kotlin 和 Go 服务。

How to use this skill

Skill file

六边形架构

六边形架构(端口与适配器)使业务逻辑独立于框架、传输和持久化细节。核心应用程序依赖于抽象端口,适配器在边缘实现这些端口。

何时使用

当请求涉及边界、以域为中心的设计、重构紧密耦合的服务或将应用程序逻辑与特定库解耦时,使用此技能。

核心概念

出站端口接口通常位于应用层(或仅在抽象真正是域级别时位于域中),而基础设施适配器实现它们。

依赖方向始终向内:

工作原理

步骤 1:建模用例边界

定义具有清晰输入和输出 DTO 的单个用例。将传输详细信息(Express req、GraphQL context、作业负载包装器)保持在此边界之外。

步骤 2:首先定义出站端口

将每个副作用识别为端口:

端口应建模能力,而非技术。

步骤 3:使用纯编排实现用例

用例类/函数通过构造函数/参数接收端口。它验证应用程序级别的不变量,协调域规则,并返回纯数据结构。

步骤 4:在边缘构建适配器

步骤 5:在组合根中连接所有内容

实例化适配器,然后将其注入用例。保持此接线集中化,以避免隐藏的服务定位器行为。

步骤 6:按边界测试

架构图

flowchart LR
  Client["客户端 (HTTP/CLI/Worker)"] --> InboundAdapter["入站适配器"]
  InboundAdapter -->|"调用"| UseCase["用例 (应用层)"]
  UseCase -->|"使用"| OutboundPort["出站端口 (接口)"]
  OutboundAdapter["出站适配器"] -->|"实现"| OutboundPort
  OutboundAdapter --> ExternalSystem["数据库/API/队列"]
  UseCase --> DomainModel["域模型"]

建议的模块布局

使用具有显式边界的功能优先组织:

src/
  features/
    orders/
      domain/
        Order.ts
        OrderPolicy.ts
      application/
        ports/
          inbound/
            CreateOrder.ts
          outbound/
            OrderRepositoryPort.ts
            PaymentGatewayPort.ts
        use-cases/
          CreateOrderUseCase.ts
      adapters/
        inbound/
          http/
            createOrderRoute.ts
        outbound/
          postgres/
            PostgresOrderRepository.ts
          stripe/
            StripePaymentGateway.ts
      composition/
        ordersContainer.ts

TypeScript 示例

端口定义

export interface OrderRepositoryPort {
  save(order: Order): Promise<void>;
  findById(orderId: string): Promise<Order | null>;
}

export interface PaymentGatewayPort {
  authorize(input: { orderId: string; amountCents: number }): Promise<{ authorizationId: string }>;
}

用例

type CreateOrderInput = {
  orderId: string;
  amountCents: number;
};

type CreateOrderOutput = {
  orderId: string;
  authorizationId: string;
};

export class CreateOrderUseCase {
  constructor(
    private readonly orderRepository: OrderRepositoryPort,
    private readonly paymentGateway: PaymentGatewayPort
  ) {}

  async execute(input: CreateOrderInput): Promise<CreateOrderOutput> {
    const order = Order.create({ id: input.orderId, amountCents: input.amountCents });

    const auth = await this.paymentGateway.authorize({
      orderId: order.id,
      amountCents: order.amountCents,
    });

    // markAuthorized 返回新的 Order 实例;它不就地修改。
    const authorizedOrder = order.markAuthorized(auth.authorizationId);
    await this.orderRepository.save(authorizedOrder);

    return {
      orderId: order.id,
      authorizationId: auth.authorizationId,
    };
  }
}

出站适配器

export class PostgresOrderRepository implements OrderRepositoryPort {
  constructor(private readonly db: SqlClient) {}

  async save(order: Order): Promise<void> {
    await this.db.query(
      "insert into orders (id, amount_cents, status, authorization_id) values ($1, $2, $3, $4)",
      [order.id, order.amountCents, order.status, order.authorizationId]
    );
  }

  async findById(orderId: string): Promise<Order | null> {
    const row = await this.db.oneOrNone("select * from orders where id = $1", [orderId]);
    return row ? Order.rehydrate(row) : null;
  }
}

组合根

export const buildCreateOrderUseCase = (deps: { db: SqlClient; stripe: StripeClient }) => {
  const orderRepository = new PostgresOrderRepository(deps.db);
  const paymentGateway = new StripePaymentGateway(deps.stripe);

  return new CreateOrderUseCase(orderRepository, paymentGateway);
};

多语言映射

跨生态系统使用相同的边界规则;仅语法和接线样式更改。

要避免的反模式

迁移策略

  1. 选择一个垂直切片(单个端点/作业),具有频繁的变更痛苦。
  2. 提取具有显式输入/输出类型的用例边界。
  3. 在现有基础设周围引入出站端口。
  4. 将编排逻辑从控制器/服务移动到用例。
  5. 保留旧适配器,但使其委托给新用例。
  6. 在新边界周围添加测试(单元 + 适配器集成)。
  7. 逐片重复;避免完全重写。

重构现有系统

测试指导(相同的六边形边界)

最佳实践检查清单

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.