Chuyển đến nội dung
Skillpedia
Lập trình chung280k · #188

hexagonal-architecture

Skill này làm gì

Skill này giúp tổ chức code của chương trình sao cho logic nghiệp vụ cốt lõi được tách khỏi các chi tiết kỹ thuật như cơ sở dữ liệu hay giao diện người dùng. Nhờ vậy code dễ hiểu, dễ test và dễ thay đổi hơn.

Khi nào nên dùng

  • ✓Khi bắt đầu một dự án mới cần dễ bảo trì.
  • ✓Khi code hiện tại lộn xộn, trộn lẫn quy tắc nghiệp vụ với công nghệ.
  • ✓Khi bạn cần kết nối chương trình với các hệ thống khác (như cơ sở dữ liệu hoặc API) mà không phải thay đổi logic cốt lõi.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/hexagonal-architecture/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/hexagonal-architecture/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để tổ chức code sao cho logic nghiệp vụ không phụ thuộc vào cơ sở dữ liệu mà chúng tôi dùng?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó hoạt động bằng cách định nghĩa các 'port' (hợp đồng) cho các tương tác bên ngoài, và các 'adapter' thực hiện những port này. Logic cốt lõi của chương trình dùng các port, còn adapter xử lý các chi tiết kỹ thuật.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Hexagonal Architecture

Hexagonal architecture (Ports and Adapters) keeps business logic independent from frameworks, transport, and persistence details. The core app depends on abstract ports, and adapters implement those ports at the edges.

When to Use

  • Building new features where long-term maintainability and testability matter.
  • Refactoring layered or framework-heavy code where domain logic is mixed with I/O concerns.
  • Supporting multiple interfaces for the same use case (HTTP, CLI, queue workers, cron jobs).
  • Replacing infrastructure (database, external APIs, message bus) without rewriting business rules.

Use this skill when the request involves boundaries, domain-centric design, refactoring tightly coupled services, or decoupling application logic from specific libraries.

Core Concepts

  • Domain model: Business rules and entities/value objects. No framework imports.
  • Use cases (application layer): Orchestrate domain behavior and workflow steps.
  • Inbound ports: Contracts describing what the application can do (commands/queries/use-case interfaces).
  • Outbound ports: Contracts for dependencies the application needs (repositories, gateways, event publishers, clock, UUID, etc.).
  • Adapters: Infrastructure and delivery implementations of ports (HTTP controllers, DB repositories, queue consumers, SDK wrappers).
  • Composition root: Single wiring location where concrete adapters are bound to use cases.

Outbound port interfaces usually live in the application layer (or in domain only when the abstraction is truly domain-level), while infrastructure adapters implement them.

Dependency direction is always inward:

  • Adapters -> application/domain
  • Application -> port interfaces (inbound/outbound contracts)
  • Domain -> domain-only abstractions (no framework or infrastructure dependencies)
  • Domain -> nothing external

How It Works

Step 1: Model a use case boundary

Define a single use case with a clear input and output DTO. Keep transport details (Express req, GraphQL context, job payload wrappers) outside this boundary.

Step 2: Define outbound ports first

Identify every side effect as a port:

  • persistence (UserRepositoryPort)
  • external calls (BillingGatewayPort)
  • cross-cutting (LoggerPort, ClockPort)

Ports should model capabilities, not technologies.

Step 3: Implement the use case with pure orchestration

Use case class/function receives ports via constructor/arguments. It validates application-level invariants, coordinates domain rules, and returns plain data structures.

Step 4: Build adapters at the edge

  • Inbound adapter converts protocol input to use-case input.
  • Outbound adapter maps app contracts to concrete APIs/ORM/query builders.
  • Mapping stays in adapters, not inside use cases.

Step 5: Wire everything in a composition root

Instantiate adapters, then inject them into use cases. Keep this wiring centralized to avoid hidden service-locator behavior.

Step 6: Test per boundary

  • Unit test use cases with fake ports.
  • Integration test adapters with real infra dependencies.
  • E2E test user-facing flows through inbound adapters.

Architecture Diagram

flowchart LR
  Client["Client (HTTP/CLI/Worker)"] --> InboundAdapter["Inbound Adapter"]
  InboundAdapter -->|"calls"| UseCase["UseCase (Application Layer)"]
  UseCase -->|"uses"| OutboundPort["OutboundPort (Interface)"]
  OutboundAdapter["Outbound Adapter"] -->|"implements"| OutboundPort
  OutboundAdapter --> ExternalSystem["DB/API/Queue"]
  UseCase --> DomainModel["DomainModel"]

Suggested Module Layout

Use feature-first organization with explicit boundaries:

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 Example

Port definitions

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

export interface PaymentGatewayPort {

…
Câu hỏi thường gặp

'Port' và 'adapter' là gì?

Port giống như hợp đồng xác định chương trình cần làm gì hoặc sẽ dùng dịch vụ bên ngoài nào. Adapter là phần triển khai cụ thể của hợp đồng đó, xử lý việc giao tiếp với cơ sở dữ liệu, API, v.v.

Tại sao gọi là 'kiến trúc lục giác'?

Tên này xuất phát từ ý tưởng coi logic nghiệp vụ cốt lõi như một hình lục giác, với các port ở mỗi cạnh để kết nối với các adapter khác nhau (giống như bàn phím, màn hình gắn vào một máy tính).

Cách này có phức tạp hơn để triển khai không?

Lúc đầu có thể thấy phức tạp hơn một chút, nhưng về lâu dài nó giúp phát triển và bảo trì dễ dàng và an toàn hơn, đặc biệt trong các dự án lớn.

Chi tiết

Mô tả gốc của tác giả

Design, implement, and refactor Ports & Adapters systems with clear domain boundaries, dependency inversion, and testable use-case orchestration across TypeScript, Java, Kotlin, and Go services. Use when introducing or refactoring toward Ports and Adapters, or when domain logic has become entangled with I/O.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#188
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự