Communityコーディング&開発github.com

アーキテクチャパターン - クリーンアーキテクチャ、ヘキサゴナルアーキテクチャ、ドメイン駆動設計

クリーンアーキテクチャ、ヘキサゴナルアーキテクチャ、ドメイン駆動設計などの実績あるバックエンドアーキテクチャパターンを実装するためのスキルです。新しいマイクロサービスの設計、モノリスから境界づけられたコンテキストへのリファクタリング、依存関係の循環のデバッグに使用します。

アーキテクチャパターン - クリーンアーキテクチャ、ヘキサゴナルアーキテクチャ、ドメイン駆動設計 とは?

このスキルは、クリーンアーキテクチャ、ヘキサゴナルアーキテクチャ(ポート&アダプター)、ドメイン駆動設計(DDD)の3つの主要なバックエンドアーキテクチャパターンを習得するための包括的なガイドです。新しいマイクロサービスの設計から、モノリスアプリケーションのリファクタリング、境界づけられたコンテキストの確立、依存関係サイクルのデバッグまで、幅広いユースケースをカバーします。各パターンの核心となる概念(レイヤー構造、依存関係のルール、インターフェース定義、テストの境界)を詳細に説明し、実際のコード例を通じて理解を深めます。特に、インメモリアダプターを用いたテスタビリティの高いコードベースの構築方法に焦点を当てており、データベースやDockerを必要としないユニットテストの実装例を示しています。さらに、DDDの戦略的パターン(境界づけられたコンテキスト、コンテキストマッピング)と戦術的パターン(エンティティ、値オブジェクト、集約、ドメインイベント)についても詳しく解説し、CQRSやサーガオーケストレーションなどの関連スキルとも連携可能な設計基盤を提供します。

対応~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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

アーキテクチャパターン

クリーンアーキテクチャ、ヘキサゴナルアーキテクチャ、ドメイン駆動設計(DDD)などの実績あるバックエンドアーキテクチャパターンを習得し、保守性、テスト容易性、拡張性に優れたシステムを構築します。

前提条件: アーキテクチャ設計対象のサービス境界またはモジュール。 成果物: 明確な依存関係ルール、インターフェース定義、テスト境界を持つレイヤー構造。

このスキルを使用するタイミング

  • 新しいバックエンドサービスやマイクロサービスをゼロから設計する場合
  • ビジネスロジックがORMモデルやHTTPの関心事に絡みついているモノリスアプリケーションをリファクタリングする場合
  • システムをサービスに分割する前に境界づけられたコンテキストを確立する場合
  • インフラストラクチャコードがドメイン層に漏れ出して依存関係サイクルが発生するデバッグを行う場合
  • ユースケーステストがデータベースを必要としないテスト容易なコードベースを作成する場合
  • ドメイン駆動設計の戦術的パターン(集約、値オブジェクト、ドメインイベント)を実装する場合

中心となる概念

1. クリーンアーキテクチャ(Uncle Bob)

レイヤー(依存関係は内側に向かって流れる):

  • エンティティ: コアとなるビジネスモデル。フレームワークのインポートは一切行わない。
  • ユースケース: アプリケーションのビジネスルール。エンティティを調整(オーケストレーション)する。
  • インターフェースアダプター: コントローラ、プレゼンター、ゲートウェイ。ユースケースと外部フォーマットを変換する。
  • フレームワークとドライバ: UI、データベース、外部サービス。すべて最も外側のリングに配置する。

主要原則:

  • 依存関係は常に内側に向かってのみ流れる。内側のレイヤーは外側のレイヤーについて何も知らない。
  • ビジネスロジックはフレームワーク、データベース、配信メカニズムから独立している。
  • すべてのレイヤー境界は抽象インターフェースを介して越えられる。
  • UI、データベース、外部サービスなしでテスト可能。

2. ヘキサゴナルアーキテクチャ(ポートとアダプター)

構成要素:

  • ドメインコア: ここにビジネスロジックが存在し、フレームワークに依存しない。
  • ポート(Ports): コアが外界とどのようにやり取りするかを定義する抽象インターフェース(駆動ポートと駆動側ポート)。
  • アダプター(Adapters): ポートの具体的な実装(PostgreSQLアダプター、Stripeアダプター、RESTアダプター)。

メリット:

  • コアに触れることなく実装を交換可能(例:PostgreSQLをDynamoDBに置き換える)。
  • テストではインメモリアダプターを使用 — Dockerは不要。
  • 技術的な決定をエッジ(外側)に先送りできる。

3. ドメイン駆動設計(DDD)

戦略的パターン:

  • 境界づけられたコンテキスト(Bounded Contexts): 1つのサブドメインに対して首尾一貫したモデルを分離する。システム全体で単一のモデルを共有しない。
  • コンテキストマッピング(Context Mapping): コンテキスト間の関係を定義する(腐敗防止層、共有カーネル、オープンホストサービス)。
  • ユビキタス言語(Ubiquitous Language): コード内のすべての用語が、ドメインエキスパートが使用する用語と一致している。

戦術的パターン:

  • エンティティ(Entities): 時間とともに変化する安定した識別子を持つオブジェクト。
  • 値オブジェクト(Value Objects): 属性によって識別される不変オブジェクト(Eメール、金額、住所)。
  • 集約(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解析とレスポンスフォーマットの範囲を超えて肥大化した場合、ロジックをユースケースクラスに抽出してください。コントローラメソッドは、リクエストの解析、ユースケースの呼び出し、レスポンスのマッピングの3つのことだけを行うべきです。

値オブジェクトのエラー発生が遅すぎる

__post_init__(Pythonの場合)またはコンストラクタで不変条件を検証し、不正な Email や Money がそもそも生成されないようにします。これにより、不良データがビジネスロジックの深部ではなく、境界で捕捉されます。

境界づけられたコンテキスト間のコンテキスト漏洩

Order コンテキストが Identity コンテキストから User エンティティをインポートしている場合、腐敗防止層(Anti-Corruption Layer)を導入してください。Order コンテキストは独自の軽量な CustomerId 値オブジェクトを持ち、明示的なインターフェースを通じてのみ Identity コンテキストを呼び出すようにします。

高度なパターン

DDDの境界づけられたコンテキストマッピング、完全なマルチサービスプロジェクトツリー、腐敗防止層の実装、オニオンアーキテクチャの比較に関する詳細については、以下を参照してください。

関連スキル

  • microservices-patterns — モノリスをサービスに分解する際に、これらのアーキテクチャパターンを適用する。
  • cqrs-implementation — CQRSのコマンド/クエリ分離の構造的基盤としてクリーンアーキテクチャを使用する。
  • saga-orchestration — サーガは明確に定義された集約境界を必要とし、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.

関連スキル