Skip to main content
architecture-patterns Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.
インストールへ移動 Skills Marketplace コミュニティが作成したAIスキルを発見・探索
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
直接コマンドでは確認用 Prompt が省略されます。実行前にソースを確認してください。
npx skills add https://github.com/foryourhealth111-pixel/Vibe-Skills --skill architecture-patternsコマンドは1行のまま表示されます。コピー前に横へスクロールして全体を確認してください。
ローカルで確認しますか?SkillsMP が現在取得できるファイルをダウンロードできます。
Zipをダウンロード ダウンロード中... このリポジトリの他の Skills Vibe Code Orchestrator (VCO) is a governed runtime entry that freezes requirements, bounds execution, and enforces verification and phase cleanup.
Full-stack software development agent for design, implementation, testing, and deployment. Use when the user explicitly asks for end-to-end project creation, feature development, bug fixing, or code refactoring.
Git提交与调试反思报告生成技能。用于分析开发过程中的错误、调试步骤和解决方案,生成结构化的中文反思报告,并创建包含报告引用的Git提交。显式请求词:反思提交、智能提交、生成调试报告、commit with reflection。
name architecture-patterns description Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.
Architecture Patterns
Master proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.
When to Use This Skill
Designing new backend systems from scratch
Refactoring monolithic applications for better maintainability
Establishing architecture standards for your team
Migrating from tightly coupled to loosely coupled architectures
Implementing domain-driven design principles
Creating testable and mockable codebases
Planning microservices decomposition
Core Concepts
1. Clean Architecture (Uncle Bob)
Layers (dependency flows inward):
Entities : Core business models
Use Cases : Application business rules
Interface Adapters : Controllers, presenters, gateways
Frameworks & Drivers : UI, database, external services
Key Principles:
Dependencies point inward
Inner layers know nothing about outer layers
Business logic independent of frameworks
Testable without UI, database, or external services
2. Hexagonal Architecture (Ports and Adapters)
Components:
Domain Core : Business logic
Ports : Interfaces defining interactions
Adapters : Implementations of ports (database, REST, message queue)
Benefits:
Swap implementations easily (mock for testing)
Technology-agnostic core
Clear separation of concerns
3. Domain-Driven Design (DDD)
Strategic Patterns:
Bounded Contexts : Separate models for different domains
Context Mapping : How contexts relate
Ubiquitous Language : Shared terminology
Tactical Patterns:
Entities : Objects with identity
Value Objects : Immutable objects defined by attributes
Aggregates : Consistency boundaries
Repositories : Data access abstraction
Domain Events : Things that happened
Clean Architecture Pattern
Directory Structure
app/
├── domain/ # Entities & business rules
│ ├── entities/
│ │ ├── user.py
│ │ └── order.py
│ ├── value_objects/
│ │ ├── email.py
│ │ └── money.py
│ └── interfaces/ # Abstract interfaces
│ ├── user_repository.py
│ └── payment_gateway.py
├── use_cases/ # Application business rules
│ ├── create_user.py
│ ├── process_order.py
│ └── send_notification.py
├── adapters/ # Interface implementations
│ ├── repositories/
│ │ ├── postgres_user_repository.py
│ │ └── redis_cache_repository.py
│ ├── controllers/
│ │ └── user_controller.py
│ └── gateways/
│ ├── stripe_payment_gateway.py
│ └── sendgrid_email_gateway.py
└── infrastructure/ # Framework & external concerns
├── database.py
├── config.py
└── logging.py
Implementation Example
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
@dataclass
class User :
"""Core user entity - no framework dependencies."""
id : str
email: str
name: str
created_at: datetime
is_active: bool = True
def deactivate (self ):
"""Business rule: deactivating user."""
self .is_active = False
def can_place_order (self ) -> bool :
"""Business rule: active users can order."""
return self .is_active
from abc import ABC, abstractmethod
from typing import Optional , List
from domain.entities.user import User
class IUserRepository (ABC ):
"""Port: defines contract, no implementation."""
@abstractmethod
async def find_by_id ( ) -> [User]:
( ) -> [User]:
( ) -> User:
( ) -> :
domain.entities.user User
domain.interfaces.user_repository IUserRepository
dataclasses dataclass
datetime datetime
uuid
:
email:
name:
:
user: User
success:
error: [ ] =
:
( ):
.user_repository = user_repository
( ) -> CreateUserResponse:
existing = .user_repository.find_by_email(request.email)
existing:
CreateUserResponse(
user= ,
success= ,
error=
)
user = User(
= (uuid.uuid4()),
email=request.email,
name=request.name,
created_at=datetime.now(),
is_active=
)
saved_user = .user_repository.save(user)
CreateUserResponse(
user=saved_user,
success=
)
domain.interfaces.user_repository IUserRepository
domain.entities.user User
typing
asyncpg
( ):
( ):
.pool = pool
( ) -> [User]:
.pool.acquire() conn:
row = conn.fetchrow(
, user_id
)
._to_entity(row) row
( ) -> [User]:
.pool.acquire() conn:
row = conn.fetchrow(
, email
)
._to_entity(row) row
( ) -> User:
.pool.acquire() conn:
conn.execute(
,
user. , user.email, user.name, user.created_at, user.is_active
)
user
( ) -> :
.pool.acquire() conn:
result = conn.execute(
, user_id
)
result ==
( ) -> User:
User(
=row[ ],
email=row[ ],
name=row[ ],
created_at=row[ ],
is_active=row[ ]
)
fastapi APIRouter, Depends, HTTPException
use_cases.create_user CreateUserUseCase, CreateUserRequest
pydantic BaseModel
router = APIRouter()
( ):
email:
name:
( ):
request = CreateUserRequest(email=dto.email, name=dto.name)
response = use_case.execute(request)
response.success:
HTTPException(status_code= , detail=response.error)
{ : response.user}
Hexagonal Architecture Pattern
class OrderService :
"""Domain service - no infrastructure dependencies."""
def __init__ (
self,
order_repository: OrderRepositoryPort,
payment_gateway: PaymentGatewayPort,
notification_service: NotificationPort
):
self .orders = order_repository
self .payments = payment_gateway
self .notifications = notification_service
async def place_order (self, order: Order ) -> OrderResult:
if not order.is_valid():
return OrderResult(success=False , error="Invalid order" )
payment = await self .payments.charge(
amount=order.total,
customer=order.customer_id
)
if not payment.success:
return OrderResult(success=False , error="Payment failed" )
order.mark_as_paid()
saved_order = await self .orders.save(order)
await self .notifications.send(
to=order.customer_email,
subject="Order confirmed" ,
body=f"Order {order.id } confirmed"
)
return OrderResult(success=True , order=saved_order)
( ):
( ) -> Order:
( ):
( ) -> PaymentResult:
( ):
( ):
( ):
( ):
.stripe = stripe
.stripe.api_key = api_key
( ) -> PaymentResult:
:
charge = .stripe.Charge.create(
amount=amount.cents,
currency=amount.currency,
customer=customer
)
PaymentResult(success= , transaction_id=charge. )
stripe.error.CardError e:
PaymentResult(success= , error= (e))
( ):
( ) -> PaymentResult:
PaymentResult(success= , transaction_id= )
Domain-Driven Design Pattern
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True )
class Email :
"""Value object: validated email."""
value: str
def __post_init__ (self ):
if "@" not in self .value:
raise ValueError("Invalid email" )
@dataclass(frozen=True )
class Money :
"""Value object: amount with currency."""
amount: int
currency: str
def add (self, other: "Money" ) -> "Money" :
if self .currency != other.currency:
raise ValueError("Currency mismatch" )
return Money(self .amount + other.amount, self .currency)
class Order :
"""Entity: has identity, mutable state."""
def __init__ ( ):
. =
.customer = customer
.items: [OrderItem] = []
.status = OrderStatus.PENDING
._events: [DomainEvent] = []
( ):
item = OrderItem(product, quantity)
.items.append(item)
._events.append(ItemAddedEvent( . , item))
( ) -> Money:
(item.subtotal() item .items)
( ):
.items:
ValueError( )
.status != OrderStatus.PENDING:
ValueError( )
.status = OrderStatus.SUBMITTED
._events.append(OrderSubmittedEvent( . ))
:
( ):
. =
.email = email
._addresses: [Address] = []
._orders: [ ] = []
( ):
( ._addresses) >= :
ValueError( )
._addresses.append(address)
( ) -> [Address]:
((a a ._addresses a.is_primary), )
:
order_id:
occurred_at: datetime = field(default_factory=datetime.now)
:
( ) -> [Order]:
( ):
._persist(order)
._publish_events(order._events)
order._events.clear()
Resources
references/clean-architecture-guide.md : Detailed layer breakdown
references/hexagonal-architecture-guide.md : Ports and adapters patterns
references/ddd-tactical-patterns.md : Entities, value objects, aggregates
assets/clean-architecture-template/ : Complete project structure
assets/ddd-examples/ : Domain modeling examples
Best Practices
Dependency Rule : Dependencies always point inward
Interface Segregation : Small, focused interfaces
Business Logic in Domain : Keep frameworks out of core
Test Independence : Core testable without infrastructure
Bounded Contexts : Clear domain boundaries
Ubiquitous Language : Consistent terminology
Thin Controllers : Delegate to use cases
Rich Domain Models : Behavior with data
Common Pitfalls
Anemic Domain : Entities with only data, no behavior
Framework Coupling : Business logic depends on frameworks
Fat Controllers : Business logic in controllers
Repository Leakage : Exposing ORM objects
Missing Abstractions : Concrete dependencies in core
Over-Engineering : Clean architecture for simple CRUD
self, user_id: str
Optional
pass
@abstractmethod
async
def
find_by_email
self, email: str
Optional
pass
@abstractmethod
async
def
save
self, user: User
pass
@abstractmethod
async
def
delete
self, user_id: str
bool
pass
from
import
from
import
from
import
from
import
import
@dataclass
class
CreateUserRequest
str
str
@dataclass
class
CreateUserResponse
bool
Optional
str
None
class
CreateUserUseCase
"""Use case: orchestrates business logic."""
def
__init__
self, user_repository: IUserRepository
self
async
def
execute
self, request: CreateUserRequest
await
self
if
return
None
False
"Email already exists"
id
str
True
await
self
return
True
from
import
from
import
from
import
Optional
import
class
PostgresUserRepository
IUserRepository
"""Adapter: PostgreSQL implementation."""
def
__init__
self, pool: asyncpg.Pool
self
async
def
find_by_id
self, user_id: str
Optional
async
with
self
as
await
"SELECT * FROM users WHERE id = $1"
return
self
if
else
None
async
def
find_by_email
self, email: str
Optional
async
with
self
as
await
"SELECT * FROM users WHERE email = $1"
return
self
if
else
None
async
def
save
self, user: User
async
with
self
as
await
"""
INSERT INTO users (id, email, name, created_at, is_active)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET email = $2, name = $3, is_active = $5
"""
id
return
async
def
delete
self, user_id: str
bool
async
with
self
as
await
"DELETE FROM users WHERE id = $1"
return
"DELETE 1"
def
_to_entity
self, row
"""Map database row to entity."""
return
id
"id"
"email"
"name"
"created_at"
"is_active"
from
import
from
import
from
import
class
CreateUserDTO
BaseModel
str
str
@router.post("/users" )
async
def
create_user
dto: CreateUserDTO,
use_case: CreateUserUseCase = Depends(get_create_user_use_case )
"""Controller: handles HTTP concerns only."""
await
if
not
raise
400
return
"user"
class
OrderRepositoryPort
ABC
@abstractmethod
async
def
save
self, order: Order
pass
class
PaymentGatewayPort
ABC
@abstractmethod
async
def
charge
self, amount: Money, customer: str
pass
class
NotificationPort
ABC
@abstractmethod
async
def
send
self, to: str , subject: str , body: str
pass
class
StripePaymentAdapter
PaymentGatewayPort
"""Primary adapter: connects to Stripe API."""
def
__init__
self, api_key: str
self
self
async
def
charge
self, amount: Money, customer: str
try
self
return
True
id
except
as
return
False
str
class
MockPaymentAdapter
PaymentGatewayPort
"""Test adapter: no external dependencies."""
async
def
charge
self, amount: Money, customer: str
return
True
"mock-123"
self, id : str , customer: Customer
self
id
id
self
self
List
self
self
List
def
add_item
self, product: Product, quantity: int
"""Business logic in entity."""
self
self
self
id
def
total
self
"""Calculated property."""
return
sum
for
in
self
def
submit
self
"""State transition with business rules."""
if
not
self
raise
"Cannot submit empty order"
if
self
raise
"Order already submitted"
self
self
self
id
class
Customer
"""Aggregate root: controls access to entities."""
def
__init__
self, id : str , email: Email
self
id
id
self
self
List
self
List
str
def
add_address
self, address: Address
"""Aggregate enforces invariants."""
if
len
self
5
raise
"Maximum 5 addresses allowed"
self
@property
def
primary_address
self
Optional
return
next
for
in
self
if
None
@dataclass
class
OrderSubmittedEvent
str
class
OrderRepository
"""Repository: persist/retrieve aggregates."""
async
def
find_by_id
self, order_id: str
Optional
"""Reconstitute aggregate from storage."""
pass
async
def
save
self, order: Order
"""Persist aggregate and publish events."""
await
self
await
self