arch-domain-driven
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePurpose
用途
This skill implements Domain-Driven Design (DDD) principles to structure code effectively. It helps generate and manage bounded contexts, aggregates, entities, value objects, and domain events, while promoting ubiquitous language for better team alignment.
该Skill实现了领域驱动设计(DDD)原则,以高效地结构化代码。它有助于生成和管理限界上下文、聚合根、实体、值对象和领域事件,同时推广通用语言以提升团队协作一致性。
When to Use
适用场景
Use this skill for complex applications with rich domain logic, such as e-commerce platforms or financial systems, where clear boundaries reduce coupling. Apply it during architecture design phases to avoid monolithic codebases, especially when dealing with multiple subdomains or legacy integrations.
当开发具有复杂领域逻辑的应用时使用该Skill,例如电商平台或金融系统,清晰的边界可降低代码耦合度。在架构设计阶段应用它,避免单体代码库,尤其是在处理多个子域或遗留系统集成时。
Key Capabilities
核心功能
- Generate bounded contexts with isolated modules for specific domains.
- Define aggregates as clusters of entities with a single root for transaction consistency.
- Create entities with identity and value objects for immutable data.
- Handle domain events to trigger reactions, like publishing to event buses.
- Enforce ubiquitous language by embedding domain terms into code and configurations.
- 为特定领域生成带有独立模块的限界上下文。
- 将聚合根定义为具有单一根实体的实体集群,确保事务一致性。
- 创建带有标识的实体和用于不可变数据的值对象。
- 处理领域事件以触发响应,例如发布到事件总线。
- 通过在代码和配置中嵌入领域术语,强制推行通用语言。
Usage Patterns
使用模式
Always begin by mapping the domain to identify bounded contexts. Use the skill to scaffold structures, then refine aggregates within contexts. For example, integrate with CI/CD by running generation commands in build scripts. Test incrementally: generate an entity, add it to an aggregate, and verify invariants. Avoid over-modeling by limiting contexts to high-cohesion areas, and use events for cross-context communication.
始终先映射领域以识别限界上下文。使用该Skill搭建基础结构,然后在上下文内细化聚合根。例如,通过在构建脚本中运行生成命令与CI/CD集成。逐步测试:生成一个实体,将其添加到聚合根中,然后验证不变量。通过将上下文限制在高内聚区域避免过度建模,并使用事件进行跨上下文通信。
Common Commands/API
常用命令/API
Interact via OpenClaw's CLI or REST API. Authentication requires setting in your environment.
$OPENCLAW_API_KEYCLI Commands:
- Generate a bounded context: This creates a directory like
openclaw ddd generate-context --name MyContext --description "User management" --language pythonwith subfolders for aggregates and entities../my_context/ - Define an aggregate: Adds files like
openclaw ddd generate-aggregate --context MyContext --name AccountAggregate --root EntityName --invariants "balance > 0"with the root entity and invariant checks.account_aggregate.py - Create an entity:
openclaw ddd generate-entity --context MyContext --name UserEntity --properties "id:UUID, name:String" - Handle domain events:
openclaw ddd generate-event --context MyContext --name UserCreatedEvent --payload "user_id:UUID"
API Endpoints:
- POST /api/v1/ddd/contexts with JSON body: Requires header:
{"name": "MyContext", "description": "User management", "language": "python"}Authorization: Bearer $OPENCLAW_API_KEY - POST /api/v1/ddd/aggregates with body:
{"context": "MyContext", "name": "AccountAggregate", "root": "Account", "invariants": ["balance > 0"]}
Config Formats:
Use YAML for configurations, e.g., in a file:
.openclaw/config.ymlddd:
default_language: python
contexts:
- name: MyContext
description: User managementCode Snippets:
- Generate and use a context in Python:
python
import openclaw.ddd as oc
oc.generate_context(name="MyContext", description="User management")
context = oc.load_context("MyContext")- Define an aggregate in code:
python
from openclaw.ddd import Aggregate
class AccountAggregate(Aggregate):
def __init__(self, account_id):
self.root = Entity(account_id) # Assuming Entity is generated通过OpenClaw的CLI或REST API进行交互。身份验证需要在环境中设置。
$OPENCLAW_API_KEYCLI命令:
- 生成限界上下文:这会创建类似
openclaw ddd generate-context --name MyContext --description "User management" --language python的目录,包含聚合根和实体的子文件夹。./my_context/ - 定义聚合根:添加类似
openclaw ddd generate-aggregate --context MyContext --name AccountAggregate --root EntityName --invariants "balance > 0"的文件,包含根实体和不变量检查。account_aggregate.py - 创建实体:
openclaw ddd generate-entity --context MyContext --name UserEntity --properties "id:UUID, name:String" - 处理领域事件:
openclaw ddd generate-event --context MyContext --name UserCreatedEvent --payload "user_id:UUID"
API端点:
- POST /api/v1/ddd/contexts,JSON请求体:需要请求头:
{"name": "MyContext", "description": "User management", "language": "python"}Authorization: Bearer $OPENCLAW_API_KEY - POST /api/v1/ddd/aggregates,请求体:
{"context": "MyContext", "name": "AccountAggregate", "root": "Account", "invariants": ["balance > 0"]}
配置格式:
使用YAML进行配置,例如在文件中:
.openclaw/config.ymlddd:
default_language: python
contexts:
- name: MyContext
description: User management代码片段:
- 在Python中生成并使用上下文:
python
import openclaw.ddd as oc
oc.generate_context(name="MyContext", description="User management")
context = oc.load_context("MyContext")- 在代码中定义聚合根:
python
from openclaw.ddd import Aggregate
class AccountAggregate(Aggregate):
def __init__(self, account_id):
self.root = Entity(account_id) # Assuming Entity is generatedIntegration Notes
集成说明
Integrate by exporting before CLI/API calls. Add OpenClaw as a dependency in your project (e.g., for Python). For IDEs, use plugins like VS Code extensions to trigger commands via keyboard shortcuts, such as binding to a key. Chain with other tools: pipe CLI output to Git for auto-commits, or use webhooks to call API endpoints from services like Jenkins. Ensure compatibility by specifying language flags (e.g., ) to match your stack.
$OPENCLAW_API_KEY=your_api_keypip install openclawopenclaw ddd generate-context--language java在调用CLI/API之前,通过导出进行配置。在项目中添加OpenClaw作为依赖(例如,Python项目使用)。对于IDE,使用VS Code扩展等插件,通过快捷键触发命令,例如将绑定到某个按键。与其他工具联动:将CLI输出管道到Git以实现自动提交,或使用Webhook从Jenkins等服务调用API端点。通过指定语言标志(例如)确保与你的技术栈兼容。
$OPENCLAW_API_KEY=your_api_keypip install openclawopenclaw ddd generate-context--language javaError Handling
错误处理
Always check CLI exit codes; non-zero indicates failure (e.g., ). For API calls, handle HTTP errors like 400 for validation failures or 401 for auth issues by checking response status. In code, wrap operations in try-except blocks:
if [ $? -ne 0 ]; then echo "Error: Invalid input"; fipython
try:
oc.generate_aggregate(context="MyContext", name="InvalidAggregate", invariants=["invalid"])
except oc.DDDValidationError as e: # Specific error for invariant checks
print(f"Error: {e.message} - Fix invariants and retry")
except oc.AuthError as e: # For $OPENCLAW_API_KEY issues
print("Error: Authentication failed - Set $OPENCLAW_API_KEY")Validate inputs upfront, e.g., ensure context names are alphanumeric via CLI flags like .
--validate始终检查CLI退出码;非零值表示失败(例如)。对于API调用,处理HTTP错误,例如400表示验证失败,401表示身份验证问题,需检查响应状态。在代码中,将操作包裹在try-except块中:
if [ $? -ne 0 ]; then echo "Error: Invalid input"; fipython
try:
oc.generate_aggregate(context="MyContext", name="InvalidAggregate", invariants=["invalid"])
except oc.DDDValidationError as e: # 针对不变量检查的特定错误
print(f"Error: {e.message} - Fix invariants and retry")
except oc.AuthError as e: # 针对$OPENCLAW_API_KEY问题
print("Error: Authentication failed - Set $OPENCLAW_API_KEY")提前验证输入,例如通过等CLI标志确保上下文名称为字母数字格式。
--validateConcrete Usage Examples
实际使用示例
-
Building a bounded context for an e-commerce order system: First, identify the domain: orders involve aggregates like Order and LineItems. Run:This outputs:
openclaw ddd generate-context --name OrderContext --description "Manages orders" --modules orders,itemsand./order_context/orders.py. Next, add an aggregate:./order_context/items.pyIn code, import and use:openclaw ddd generate-aggregate --context OrderContext --name OrderAggregate --root Order --invariants "total > 0"from order_context.aggregates import OrderAggregate; order = OrderAggregate(order_id=1) -
Handling domain events in a user registration flow: Start by generating the event:This creates
openclaw ddd generate-event --context UserContext --name UserRegisteredEvent --payload "user_id:UUID, email:String". Then, trigger it via API:./user_context/events/user_registered_event.pyIn your application code:curl -H "Authorization: Bearer $OPENCLAW_API_KEY" -X POST /api/v1/ddd/events -d '{"context": "UserContext", "event": "UserRegisteredEvent", "payload": {"user_id": "123"}}'to notify other services.oc.publish_event(context="UserContext", event="UserRegisteredEvent", payload={"user_id": "123"})
-
为电商订单系统构建限界上下文: 首先,识别领域:订单涉及Order和LineItems等聚合根。运行:输出:
openclaw ddd generate-context --name OrderContext --description "Manages orders" --modules orders,items和./order_context/orders.py。接下来,添加聚合根:./order_context/items.py在代码中导入并使用:openclaw ddd generate-aggregate --context OrderContext --name OrderAggregate --root Order --invariants "total > 0"from order_context.aggregates import OrderAggregate; order = OrderAggregate(order_id=1) -
在用户注册流程中处理领域事件: 首先生成事件:这会创建
openclaw ddd generate-event --context UserContext --name UserRegisteredEvent --payload "user_id:UUID, email:String"。然后,通过API触发它:./user_context/events/user_registered_event.py在你的应用代码中:curl -H "Authorization: Bearer $OPENCLAW_API_KEY" -X POST /api/v1/ddd/events -d '{"context": "UserContext", "event": "UserRegisteredEvent", "payload": {"user_id": "123"}}'以通知其他服务。oc.publish_event(context="UserContext", event="UserRegisteredEvent", payload={"user_id": "123"})
Graph Relationships
关联关系
- Related to cluster: se-architecture (e.g., shares dependencies with other architecture skills).
- Connected via tags: ddd (links to domain modeling tools), domain (connects to entity management skills), bounded-context (relates to microservices patterns), architecture (ties into se-architecture cluster for broader design tools).
- 关联集群:se-architecture(例如,与其他架构Skill共享依赖)。
- 通过标签连接:ddd(链接到领域建模工具)、domain(连接到实体管理Skill)、bounded-context(与微服务模式相关)、architecture(与se-architecture集群关联,用于更广泛的设计工具)。