English | 中文README
dddfirework 是一个支持 DDD (领域驱动设计)实现的引擎框架,他提供对领域实体从创建,修改,持久化,发送事件,事件监听等完整生命周期的封装,以及锁,数据库,事件总线等组件的集成。

定义领域实体
import ddd "github.com/bytedance/dddfirework"
type Order struct {
ddd.BaseEntity
UserID string
TotalAmount int64
Remark string
}
注册持久化模型
import ddd "github.com/bytedance/dddfirework"
import "github.com/bytedance/dddfirework/executor/mysql"
func init() {
mysql.RegisterEntity2Model(&domain.Order{}, func(entity, parent ddd.IEntity, op ddd.OpType) (mysql.IModel, error) {
do := entity.(*domain.Order)
return &po.OrderPO{
ID: do.GetID(),
User: do.UserID,
TotalAmount: do.TotalAmount,
Remark: do.Remark,
}, nil
}, func(m mysql.IModel, do ddd.IEntity) error {
orderPO, order := m.(*po.OrderPO), do.(*domain.Order)
order.UserID = orderPO.User
order.TotalAmount = orderPO.TotalAmount
order.Remark = orderPO.Remark
return nil
}
}
定义命令 (Command)
type UpdateOrderOpt struct {
Remark *string
}
type UpdateOrderCommand struct {
ddd.Command
orderID string
opt UpdateOrderOpt
}
func NewUpdateOrderCommand(orderID string, opt UpdateOrderOpt) *UpdateOrderCommand {
return &UpdateOrderCommand{
orderID: orderID,
opt: opt,
}
}
func (c *UpdateOrderCommand) Init(ctx context.Context) (lockIDs []string, err error) {
return []string{c.orderID}, nil
}
func (c *UpdateOrderCommand) Build(ctx context.Context, builder dddfirework.DomainBuilder) (roots []dddfirework.IEntity, err error) {
order := &domain.Order{
ID: id,
Items: []*domain.SaleItem{},
Coupons: []*domain.Coupon{},
}
if err := builder.Build(ctx, order, &order.Items, &order.Coupons); err != nil {
return nil, err
}
return []dddfirework.IEntity{order}, nil
}
func (c *UpdateOrderCommand) Act(ctx context.Context, container dddfirework.RootContainer, roots ...dddfirework.IEntity) error {
order := roots[0].(*domain.Order)
if c.opt.Remark != nil {
order.Remark = *c.opt.Remark
order.Dirty()
}
return nil
}
执行命令
import (
ddd "github.com/bytedance/dddfirework"
db_executor "github.com/bytedance/dddfirework/executor/mysql"
db_eventbus "github.com/bytedance/dddfirework/eventbus/mysql"
db_lock "github.com/bytedance/dddfirework/lock/db"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
lock := db_lock.NewDBLock(db, time.Second*10)
executor := db_executor.NewExecutor(db)
eventBus := db_eventbus.NewEventBus("svc_example", db)
engine := dddfirework.NewEngine(lock, executor, eventBus.Options()...)
engine.RunCommand(ctx, command.NewUpdateOrderCommand(
req.ID, command.UpdateOrderOpt{Remark: req.Remark},
))
}
参考: example/main.go
$ claude mcp add dddfirework \
-- python -m otcore.mcp_server <graph>