# 在 Go 中结合 DDD、CQRS 和整洁架构 (Clean Architecture) * **Robert Laszczak** (Three Dots Labs 联合创始人,Watermill 的创造者,《Go With The Domain》的作者) 在[之前的文章](https://threedots.tech/series/modern-business-software-in-go/)中,我们介绍了诸如 **DDD 精简版 (DDD Lite)**、**CQRS** 和**整洁(六边形)架构 (Clean/Hexagonal Architecture)** 等技术。即使单独使用,它们也各有益处。但它们结合在一起时效果最佳——就像“超凡战队 (Power Rangers)”一样。遗憾地是,在真实项目中将它们结合在一起并不简单。 **在这篇文章中,我将向你展示如何以最实用、最高效的方式将 DDD 精简版、CQRS 和整洁架构连接在一起。** ### 我为什么要关心这个? 从事编程项目类似于规划和建造一个住宅区。如果你知道这个区域在不久的将来会扩张,你需要为未来的改进留出空间。即使在开始时,这看起来像是浪费空间。你应该为未来的设施,如住宅楼、医院和寺庙预留空间。**如果不这样做,你将不得不清理现有的建筑和街道,以为新的腾出空间。** 最好早点考虑这一点。 ![Empty district](https://threedots.tech/media/ddd-cqrs-clean-architecture-combined/district-empty_hu220d4ff6c72c1d6020e531f239fbe9c2_271317_2000x1083_resize_q80_h2_lanczos_3.webp) 代码的情况也是如此。如果你知道项目将开发超过一个月,你应该从一开始就考虑到长期目标。**你需要以不会阻碍未来工作的方式来编写代码。即使起初它看起来像是过度设计以及大量的样板代码,你也必须考虑长远利益。** 这并不意味着你需要规划未来要实施的所有功能——恰恰相反。这种方法帮助你适应新的需求或是对业务领域理解的改变。这里不需要大规模的前置设计 (Big upfront design)。在当下,世界变化迅速,无法适应的公司将很快倒闭,这一点至关重要。 ![Full district](https://threedots.tech/media/ddd-cqrs-clean-architecture-combined/district-full_hu4591c93297b951538442105f8fe9960b_269516_2000x1083_resize_q80_h2_lanczos_3.webp) **这正是当你结合这些模式时它们带给你的:保持持续开发速度的能力,而无需破坏或过多触碰现有代码。** 这需要更多的思考和规划吗?这是一种更具挑战性的方式吗?你需要拥有额外的知识才能做到吗?当然!**但长期的结果值得这样做!** 幸运的是,你来对地方了。 😉 让我们把理论抛在脑后。让我们开始写代码。在这篇文章中,我们将跳过对设计选择的推理。这些我们在[之前的文章](https://threedots.tech/series/modern-business-software-in-go/)中已经描述过。如果你还没有读过,我建议你阅读——你会更好地理解这篇文章。 如同之前的文章,我们将基于重构一个真实的开源项目来构建我们的代码。这应该使示例更加真实,并适用于你自己的项目。 准备好了吗? 注意 #### 这不仅仅是又一篇充斥着随机代码片段的文章。 这篇文章是我们更大系列的一部分,在该系列中,我们展示如何构建**易于开发、维护并在长期内令人愉快的工作的 Go 应用程序。** 我们通过分享基于许多我们带领团队进行的实验以及[科学研究](https://threedots.tech/post/ddd-lite-in-go-introduction/?utm_source=about-wild-workouts#thats-great-but-do-you-have-any-evidence-it-works)证明的技术来实现这一目标。 你可以通过与我们一起构建一个[完全功能性的](https://threedots.tech/post/serverless-cloud-run-firebase-modern-go-application/?utm_source=about-wild-workouts#what-wild-workouts-can-do)示例 Go Web 应用程序 —— **Wild Workouts** 来学习这些模式。 我们做了一件不同的事——**我们在初始的 Wild Workouts 实现中加入了一些细微的问题**。是我们疯了吗?还没有。 😉 这些问题在 Go 项目中很常见。**从长远来看,这些小的问题会变得至关重要并阻止添加新功能。** **这正是一名高级或主管开发人员的基本技能之一;你总是需要记住长期的影响。** 我们将通过 **重构** Wild Workouts 来修复这些问题。这样,你将快速理解我们分享的技术。 你是否知道那种感觉:读完一篇关于某项技术的文章后,试图只因为指南中跳过了一些问题而受阻?省略这些细节使文章更短并增加了页面浏览量,但这不是我们的目标。我们的目标是创建提供足够相关知识的应用教程。如果你还没有阅读[系列中的之前的文章](https://threedots.tech/series/modern-business-software-in-go/?utm_source=about-wild-workouts),我们强烈建议你去看看。 我们认为在某些领域没有捷径。如果你想以快速高效的方式构建复杂的应用程序,你需要花时间学习。如果这很简单,我们就不会有大量令人恐惧的遗留代码。 这是目前发布的 **[14 篇文章的完整列表](https://threedots.tech/series/modern-business-software-in-go/?utm_source=about-wild-workouts)**。 **Wild Workouts 的完整源代码** 可以在 [GitHub](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example?utm_source=about-wild-workouts) 上找到。别忘了给我们的项目点个 Star!⭐ ### 让我们开始重构 让我们从 [领域优先 (Domain-First)](https://threedots.tech/post/ddd-lite-in-go-introduction/#domain-first-approach) 方法开始我们的重构。我们将从引入 [领域层 (domain layer)](https://threedots.tech/post/introducing-clean-architecture/#the-dependency-inversion-principle) 开始。这可以确保实现细节不会影响我们的领域代码。**我们还可以将所有精力投入到理解业务问题,而不是编写枯燥的数据库查询和 API 端点。** 领域优先方法既适用于救援(重构 😉)也适用于从零开始 (greenfield) 的项目。 为了开始构建我的领域层,我需要确定应用程序实际上在做什么。本文将重点介绍 Wild Workouts 微服务 `trainings` 的重构([github.com/tree.../internal/trainings](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/tree/v2.5/internal/trainings))。我首先通过识别应用程序处理用例来开始工作。在此之前对 [整洁架构](https://threedots.tech/post/introducing-clean-architecture/) 的重构后,你可以在 [`TrainingService`](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/v2.4/internal/trainings/app/training_service.go#L32) 中找到它。当我使用混乱的应用程序工作时,我会查看 RPC 和 HTTP 端点以找到支持的用例。 我识别出的功能之一是**培训改期审批**。在 Wild Workouts 中,如果改期请求是在培训日期前不到 24 小时提出的,则需要进行培训改期审批。如果学员请求改期,培训师需要批准。如果培训师请求改期,学员需要接受。 ```go func (c TrainingService) ApproveTrainingReschedule(ctx context.Context, user auth.User, trainingUUID string) error { return c.repo.ApproveTrainingReschedule(ctx, trainingUUID, func(training Training) (Training, error) { // 检查是否有提议的新时间 if training.ProposedTime == nil { return Training{}, errors.New("training has no proposed time") } // 检查是否有提议改期的用户类型 if training.MoveProposedBy == nil { return Training{}, errors.New("training has no MoveProposedBy") } // 如果是培训师提议的,则学员需要审批 if *training.MoveProposedBy == "trainer" && training.UserUUID != user.UUID { return Training{}, errors.Errorf("user '%s' cannot approve reschedule of user '%s'", user.UUID, training.UserUUID) } // 请求改期的人不能自己审批 if *training.MoveProposedBy == user.Role { return Training{}, errors.New("reschedule cannot be accepted by requesting person") } // 更新培训时间 training.Time = *training.ProposedTime training.ProposedTime = nil return training, nil }) } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63) ### 从领域开始 即使这看起来并非你最见过的最糟糕的代码,函数如 `ApproveTrainingReschedule` 随时间推移往往会变得更复杂。更复杂的函数意味着未来开发中更多的潜在错误。 如果你是新项目的新手,并且缺乏关于该项目的_“萨满知识”_(shaman knowledge,指对底层历史逻辑的理解),这更有可能发生。**你应该始终考虑将来会参与项目的每一个人,并使你的代码抵抗被他们无意中打破的风险。** 这将帮助你的项目避免变成大家都不敢触碰的遗留代码。你可能知道当你对一个项目陌生时,因为害怕破坏系统而对什么都畏手畏脚的感觉。 人们换工作的频率超过每两年一次的频率并不少见。这使得对于项目的长期开发变得更加关键。 如果你不相信这段代码会变得更复杂,我建议你查看你在最糟糕的项目位置的 Git 历史记录。在大多数情况下,最糟糕的代码始于_"只是一两个简单的 if"_。 😉 代码越复杂,后续简化就越困难。**我们应该对日益增加的复杂性保持敏感,并尽快尝试简化它们。** #### `Training` 领域实体 (Entity) 在分析当前由 `trainings` 微服务处理的使用例时,我发现它们都与一个_课程/培训 (training)_有关。自然地,创建一个 `Training` 类型来处理这些操作。 ![Service methods](https://threedots.tech/media/ddd-cqrs-clean-architecture-combined/training-svc-methods_hu23e5b80bfce1cbb76338ba1eb2a6298a_91843_833x288_resize_q80_h2_lanczos.webp) 重构后的 [TrainingService](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/v2.4/internal/trainings/app/training_service.go#L32) 方法 注意 #### 名词 == 实体 这是一种有效发现实体的方法吗?嗯,其实不是。 DDD 提供了帮助我们建立复杂领域模型而无需猜测的工具(_战略 DDD 模式_, _聚合 (Aggregates)_)。我们不希望猜测我们的聚合是什么样子的——我们需要工具来发现它们。事件风暴 (Event Storming) 技术在这里非常有用……但这将是另一整篇文章的话题。 这个话题足够复杂,值得写几篇文章。这也是我们稍后要做的事情。 😉 这是否意味着你不应该在没有战略 DDD 模式的情况下使用这些技术?当然不是!当前的方法对于较简单的项目可能足够好。不幸的是(或者幸运的是 😉),并非所有项目都是简单的。 ```go package training // ... type Training struct { uuid string userUUID string userName string time time.Time notes string proposedNewTime time.Time moveProposedBy UserType // 提议改期的用户类型 (Trainer/Attendee) canceled bool // 是否已取消 } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/training.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L10) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L10) 所有字段都是私有的,以提供封装。这对于满足关于 DDD 精简版文章中的 [“始终在内存中保持有效状态”](https://threedots.tech/post/ddd-lite-in-go-introduction/#the-second-rule-always-keep-a-valid-state-in-the-memory) 规则至关重要。 得益于构造函数中的验证和封装的字段,我们可以确保 `Training` 始终是有效的。**现在,对 project 一无所知的人无法以错误的方式使用它。** 同样的规则适用于 `Training` 提供的任何方法。 ```go package training func NewTraining(uuid string, userUUID string, userName string, trainingTime time.Time) (*Training, error) { if uuid == "" { return nil, errors.New("empty training uuid") } if userUUID == "" { return nil, errors.New("empty userUUID") } if userName == "" { return nil, errors.New("empty userName") } if trainingTime.IsZero() { return nil, errors.New("zero training time") } return &Training{ uuid: uuid, userUUID: userUUID, userName: userName, time: trainingTime, }, nil } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/training.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L25) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/training.go#L25) #### 在领域层审批改期 如 [DDD 精简版介绍](https://threedots.tech/post/ddd-lite-in-go-introduction/#the-first-rule---reflect-your-business-logic-literally) 中所述,我们使用基于行为而非数据的面向行为的方法来构建我们的领域。让我们在领域实体上对 `ApproveReschedule` (审批改期) 进行建模。 ```go package training // ... func (t *Training) IsRescheduleProposed() bool { // 检查是否有提议改期的用户类型和新时间 return !t.moveProposedBy.IsZero() && !t.proposedNewTime.IsZero() } var ErrNoRescheduleRequested = errors.New("no training reschedule was requested yet") func (t *Training) ApproveReschedule(userType UserType) error { // 如果没有提出改期请求,则不允许审批 if !t.IsRescheduleProposed() { return errors.WithStack(ErrNoRescheduleRequested) } // 如果是提议改期的同一用户类型,则不能审批 if t.moveProposedBy == userType { return errors.Errorf( "trying to approve reschedule by the same user type which proposed reschedule (%s)", userType.String(), ) } // 更新正式时间 t.time = t.proposedNewTime // 重置提议的时间 t.proposedNewTime = time.Time{} t.moveProposedBy = UserType{} return nil } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/reschedule.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/reschedule.go#L47) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/reschedule.go#L47) 如果你还没有机会阅读: * [DDD 精简版介绍](https://threedots.tech/post/ddd-lite-in-go-introduction/), * [引入整洁架构](https://threedots.tech/post/introducing-clean-architecture/), * [引入基础 CQRS](https://threedots.tech/post/basic-cqrs-in-go/), * [仓储模式](https://threedots.tech/post/repository-pattern-in-go/)。 我强烈建议你检查它们。它们将帮助你更好地理解这篇文章。它们解释了我们将在这篇文章中结合的决策和技术。 ### 用命令编排 现在,应用层 (application layer) 可以只负责流程的编排。那里没有领域逻辑。**我们将所有的业务复杂性隐藏在领域层中。这正是我们的目标。** 为了获取和保存培训,我们使用 [仓储模式 (Repository Pattern)](https://threedots.tech/post/repository-pattern-in-go/)。 ```go package command // ... func (h ApproveTrainingRescheduleHandler) Handle(ctx context.Context, cmd ApproveTrainingReschedule) (err error) { defer func() { logs.LogCommandExecution("ApproveTrainingReschedule", cmd, err) }() // 调用仓库更新培训 return h.repo.UpdateTraining( ctx, cmd.TrainingUUID, cmd.User, func(ctx context.Context, tr *training.Training) (*training.Training, error) { originalTrainingTime := tr.Time() // 调用领域方法执行审批逻辑 if err := tr.ApproveReschedule(cmd.User.Type()); err != nil { return nil, err } // 通知培训师服务进行实际的培训更新 err := h.trainerService.MoveTraining(ctx, tr.Time(), originalTrainingTime) if err != nil { return nil, err } return tr, nil }, ) } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/app/command/approve_training_reschedule.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/approve_training_reschedule.go#L39) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/approve_training_reschedule.go#L39) ### 重构培训取消逻辑 (Cancelation) 现在让我们看看 `TrainingService` 中的 `CancelTraining`。 领域逻辑很简单:你可以在培训日期前 24 小时取消培训。如果在培训前不到 24 小时而你想取消: * 如果你是培训师,学员将“找回”他们的课程,外加一次额外的课程(没有人喜欢在同一天改变计划!) * 如果你是学员,你将失去这次课程 当前实现的样子如下: ```go func (c TrainingService) CancelTraining(ctx context.Context, user auth.User, trainingUUID string) error { return c.repo.CancelTraining(ctx, trainingUUID, func(training Training) error { // 权限检查 if user.Role != "trainer" && training.UserUUID != user.UUID { return errors.Errorf("user '%s' is trying to cancel training of user '%s'", user.UUID, training.UserUUID) } var trainingBalanceDelta int // 课程余额的变化量 if training.CanBeCancelled() { // 直接退还课程 trainingBalanceDelta = 1 } else { if user.Role == "trainer" { // 取消的课程+1 培训师不足24小时取消的“罚款” trainingBalanceDelta = 2 } else { // 不足24小时取消课程的“罚款” trainerBalanceDelta = 0 } } if trainingBalanceDelta != 0 { err := c.userService.UpdateTrainingBalance(ctx, training.UserUUID, trainingBalanceDelta) if err != nil { return errors.Wrap(err, "unable to change trainings balance") } } err := c.trainerService.CancelTraining(ctx, training.Time) if err != nil { return errors.Wrap(err, "unable to cancel training") } return nil }) } ``` 你可以看到在取消期间计算课程余额差的某种“算法”。这在应用层中不是一个好兆头。 像这样的逻辑应该存在于我们的领域层中。**如果你在应用层中开始看到与逻辑相关的 `if` 语句,你应该考虑如何将其移动到领域层。** 这将更容易在其他地方进行测试和重用。 这取决于项目,但通常**领域逻辑在初始开发后相当稳定,可以长期保持不变得存在**。它可以经受住服务之间、框架更改、库更改和 API 更改的迁移。得益于这种分离,我们可以以更安全、更快的速度进行所有这些更改。 让我们将 `CancelTraining` 方法分解为多个分离的部分。这将允许我们独立地测试和更改它们。 首先,我们需要处理取消逻辑并将 `Training` 标记为已取消。 ```go package training func (t Training) CanBeCanceledForFree() bool { return t.time.Sub(time.Now()) >= time.Hour*24 } var ErrTrainingAlreadyCanceled = errors.New("training is already canceled") func (t *Training) Cancel() error { if t.IsCanceled() { return ErrTrainingAlreadyCanceled } t.canceled = true return nil } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel.go#L14) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel.go#L14) 这里没有什么复杂的。那很好! 需要移动的第二个部分是取消后计算课程余额的“算法”。在理论上,我们可以将其放在 `Cancel()` 方法中,但在我看来,这会打破[单一职责原则](https://en.wikipedia.org/wiki/Single-responsibility_principle)和 [CQS](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation)。而且我喜欢简短的函数。 但我们应该把它放在哪里?某个对象?领域服务?在一些以 _J_ 开头并以 _ava_ 结尾的语言中(指 Java),这样是有意义的。但在 Go 中,简单地创建一个函数就足够了。 ```go package training // CancelBalanceDelta 返回在取消培训后应该调整的课时余额变化量。 func CancelBalanceDelta(tr Training, cancelingUserType UserType) int { if tr.CanBeCanceledForFree() { // 只是退还课程 return 1 } switch cancelingUserType { case Trainer: // 1 用于取消的课程 +1 作为培训师在培训前不到 24 小时取消的“罚款” return 2 case Attendee: // 作为在培训前不到 24 小时取消的“罚款” return 0 default: panic(fmt.Sprintf("not supported user type %s", cancelingUserType)) } } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/cancel_balance.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/cancel_balance.go#L6) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/cancel_balance.go#L6) 代码现在很直白。**我可以想象,我可以坐下来与任何非技术人员一起浏览这段代码,解释它是如何工作的。** 那测试呢?这可能会有点争议,但在我看来,这里的测试是多余的。测试代码将复制函数的实现。算法中的任何更改都将需要复制逻辑到测试中。我不会在这里编写测试,但如果你能因此睡个好觉——为什么不呢! #### 移动 CancelTraining 到命令处理器 我们的领域已经准备好了,所以现在让我们使用它。我们将以与之前相同的方式做到这一点: 1. 从仓库获取实体, 2. 编排领域事情, 3. 调用外部 `trainer` 服务来取消培训(该服务是“培训师日历”的真值来源), 4. 返回实体以保存到数据库。 ```go package command // ... func (h CancelTrainingHandler) Handle(ctx context.Context, cmd CancelTraining) (err error) { defer func() { logs.LogCommandExecution("CancelTrainingHandler", cmd, err) }() return h.repo.UpdateTraining( ctx, cmd.TrainingUUID, cmd.User, func(ctx context.Context, tr *training.Training) (*training.Training, error) { // 1. 执行领域取消逻辑 if err := tr.Cancel(); err != nil { return nil, err } // 2. 计算余额变化(如果需要) if balanceDelta := training.CancelBalanceDelta(*tr, cmd.User.Type()); balanceDelta != 0 { err := h.userService.UpdateTrainingBalance(ctx, tr.UserUUID(), balanceDelta) if err != nil { return nil, errors.Wrap(err, "unable to change trainings balance") } } // 3. 调用外部服务取消实际日程 if err := h.trainerService.CancelTraining(ctx, tr.Time()); err != nil { return nil, errors.Wrap(err, "unable to cancel training") } return tr, nil }, ) } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/app/command/cancel_training.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/cancel_training.go#L36) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/app/command/cancel_training.go#L36) ### 仓储重构 最初的仓储实现非常棘手,因为我为每个用例都使用了自定义方法。 ```go type trainingRepository interface { FindTrainingsForUser(ctx context.Context, user auth.User) ([]Training, error) AllTrainings(ctx context.Context) ([]Training, error) CreateTraining(ctx context.Context, training Training, createFn func() error) error CancelTraining(ctx context.Context, trainingUUID string, deleteFn func(Training) error) error RescheduleTraining(ctx context.Context, trainingUUID string, newTime time.Time, updateFn func(Training) (Training, error)) error ApproveTrainingReschedule(ctx context.Context, trainingUUID string, updateFn func(Training) (Training, error)) error RejectTrainingReschedule(ctx context.Context, trainingUUID string, updateFn func(Training) (Training, error)) error } ``` 得益于引入 `training.Training` 实体,我们可以有一个简单得多的版本:一个用于添加新培训,一个用于更新。 ```go package training // ... type Repository interface { AddTraining(ctx context.Context, tr *Training) error GetTraining(ctx context.Context, trainingUUID string, user User) (*Training, error) UpdateTraining( ctx context.Context, trainingUUID string, user User, updateFn func(ctx context.Context, tr *Training) (*Training, error), ) error } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/domain/training/repository.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/repository.go#L16) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/domain/training/repository.go#L16) 如 [上一篇文章](https://threedots.tech/post/repository-pattern-in-go/) 中所述,我们使用 Firestore 实现了我们的仓储。我们也将在此实现中使用 Firestore。请记住,这是一个实现细节——你可以使用任何你想要的数据库。在上一篇文章中,我们展示了使用不同数据库的示例实现。 ```go package adapters // ... func (r TrainingsFirestoreRepository) UpdateTraining( ctx context.Context, trainingUUID string, user training.User, updateFn func(ctx context.Context, tr *training.Training) (*training.Training, error), ) error { trainingsCollection := r.trainingsCollection() // 使用 Firestore 事务确保原子性更新 return r.firestoreClient.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error { documentRef := trainingsCollection.Doc(trainingUUID) firestoreTraining, err := tx.Get(documentRef) if err != nil { return errors.Wrap(err, "unable to get actual docs") } tr, err := r.unmarshalTraining(firestoreTraining) if err != nil { return err } // 权限检查 if err := training.CanUserSeeTraining(user, *tr); err != nil { return err } // 调用传入的函数执行领域变更 updatedTraining, err := updateFn(ctx, tr) if err != nil { return err } return tx.Set(documentRef, r.marshalTraining(updatedTraining)) }) } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/adapters/trainings_firestore_repository.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/adapters/trainings_firestore_repository.go#L83) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/adapters/trainings_firestore_repository.go#L83) ### 连接一切 我们现在如何使用我们的代码?我们的端口层 (ports layer) 呢?得益于 Miłosz 在 [重构到整洁架构](https://threedots.tech/post/introducing-clean-architecture/) 文章中做的重构,我们的端口层与其他层隔离。因此,在这次重构之后,它几乎不需要重大更改。我们只需调用应用命令而不是应用服务。 ![Clean Architecture](https://threedots.tech/media/introducing-clean-architecture/clean-arch-2_hua2fbaee330357286a5d6d11d974a364a_220043_2000x2000_resize_q80_h2_lanczos.webp) 整洁/六边形架构层。 ```go package ports // ... type HttpServer struct { app app.Application } // ... func (h HttpServer) CancelTraining(w http.ResponseWriter, r *http.Request) { trainingUUID := r.Context().Value("trainingUUID").(string) user, err := newDomainUserFromAuthUser(r.Context()) if err != nil { httperr.RespondWithSlugError(err, w, r) return } // 直接调用命令处理器 err = h.app.Commands.CancelTraining.Handle(r.Context(), command.CancelTraining{ TrainingUUID: trainingUUID, User: user, }) if err != nil { httperr.RespondWithSlugError(err, w, r) return } } ``` 完整源代码: [github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainings/ports/http.go](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/ports/http.go#L87) [完整源代码](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/blob/8d9274811559399461aa9f6bf3829316b8ddfb63/internal/trainings/ports/http.go#L87) ### 如何在真实项目中处理此类重构? 你可能不清楚如何在真实项目中执行此类重构。这在团队中很难进行代码审查并就此重构方向达成一致。 根据我的经验,最好的方法是[结对编程 (Pair)](https://en.wikipedia.org/wiki/Pair_programming) 或[群聚编程 (Mob)](https://en.wikipedia.org/wiki/Mob_programming)。即使在起初你觉得这浪费时间,知识共享和即时审查将在未来节省大量时间。由于出色的知识共享,在项目或重构后的初始阶段后,你可以工作得更快。 在这种情况下,不要考虑为 Mob/Pair 编程“丧失”了时间。你应该考虑如果不这样做你可能会失去的时间。它还将帮助你更快地完成重构,因为你不需要等待决策。你可以立即就它们达成一致。 Mob 和结对编程在实施复杂的、从零开始 (greenfield) 的项目时也非常有效。在这种情况下,知识共享尤其是一项重要的投资。我曾多次目睹这种方法如何使团队在长期内快速推进项目。 当你进行重构时,一致同意合理的时间盒也非常关键。**并且坚持它们。** 当你花费整整一个月的时间来重构而改进不明显时,你很快就会失去利益相关者的信任。快速集成和部署你的重构工作也至关重要。理想情况下,是每天一次(如果你能完成非重构工作,我相信你也可以完成重构工作!)。如果你的更改长时间未合并且未部署,会增加破坏功能的风险。它还会阻止任何在重构服务中的工作,或使更改更难合并(通常不可能在所有其他开发周围停止)。 但你如何知道项目的复杂程度是否足以使用群聚编程?不幸的是,没有魔法公式可以解答。但有一些问题你应该问自己: * 我们理解该领域吗? * 我们知道如何实现它吗? * 这最终会产生一个没有人能够审查的庞大拉取请求吗? * 如果不进行 Mob/结对编程而在知识共享上冒险,后果我们能承受吗? ### 总结 我们来到了结尾。 😄 本次重构的完整更改可以在我们的 [Wild Workouts GitHub](https://github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/commit/8d9274811559399461aa9f6bf3829316b8ddfb63) 上找到(注意,这非常庞大!)。 如果你还没有机会阅读[之前的文章](series/modern-business-software-in-go/),你知道该怎么做了!即使其中一些使用的方法是简化的,你也应该能够在你的项目中使用它们并看到价值。 我希望在这篇文章之后,你也看到了所有引入的模式是如何很好地协同工作的。如果还没有,别担心。**我花了三年时间才将所有细节连接起来。** 但时间花得值。当我的团队和我了解了所有的连接方式后,我开始以完全不同的方式看待新项目。这使我能够以更高效的长期方式工作。 值得一提的是,就像所有技术一样,这种组合不是万能灵药。如果你正在创建一个并不复杂且在开发一个月后很久都不会被涉及的项目,可能只需将一切放在一个 `main` 包中就足够了。 😉 只是记住,当那一个月的开发变成一年时该怎么做! 我们还将在此后的文章中继续这些主题。我们将很快转向 _战略 DDD 模式 (Strategic DDD Patterns)_,这应该也能帮助你从更高层面看待你的项目。 这篇文章是否帮助你理解了如何将 DDD、整洁架构和 CQRS 结合在一起?还有什么不清楚的地方吗?请在评论中告诉我们!我们很乐意讨论你的所有问题! 你喜欢这篇文章吗? -------------------------- 我们创作了大量新的有用内容。当新帖子出现时,我们可以通知你。你的电子邮件是安全的,不会分享给任何人。 🔒 你还将收到免费的 ["Go With The Domain" 电子书](https://threedots.tech/go-with-the-domain/)!