一个关于DDD、5层模型和业务逻辑的问题

发布于 2024-10-29 04:41:08 字数 1432 浏览 12 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原野 2024-11-05 04:41:08

所以,这就是 5 层(如果我误解了什么,请纠正我)。

我认为就代码而言,人们通常会将数据存储、ORM 和存储库分组在一个“层”中。另外,不要忘记演示。

如果我有业务逻辑
与单个实体相关,我应该
在实体中实现它,或者在
服务?

是的,如果它是与实体相关的行为,那么它应该驻留在实体内。实体不应该只是简单的数据容器,实体/模型层应该封装与业务模型相关的数据结构和行为。这样,如果您需要在另一个应用程序中重用模型层,则不必四处挖掘以找到卡在其他层中的相关行为。

例如,如果我有一个帖子并想要检索其所有已批准的评论,>应该是 Post.getApprovedComments (实体)还是 > CommentsService.getApprovedCommentsForPost(帖子)?

如果不了解更多关于您的架构和 ORM 的信息,很难说。我可能会选择 Post.. 路线(评论应该是 Post 实体上的集合),然后 getApprovedComments 可以是一个简单的 linq 查询等。您建议的基于服务的方法对我来说看起来不太面向对象。

(不,使用 post.getComments().filter(c -> comment.approved) 是不对的,因为这会将业务逻辑移出模型。以防万一有人问起。)

我不完全确定我同意和你在一起。对于这么简单的事情,有些人可能会认为可以接受。

我想补充一点:

服务(处理业务逻辑,例如获取按标题字母顺序排列的 5 个最新帖子,使用存储库)

……在我看来,这不是一个很好的服务示例。在此示例中,服务层没有执行任何操作 - 这应该只是 PostRepository 中定义的查询方法。

希望其中一些能有所帮助......

So, this is are the 5 tiers (please correct me if I misunderstood something).

I think often people will group Data Storage, ORM and the Repository in one 'layer' as far as your code is concerned. Also, don't forget about presentation.

If I have business logic that is
related to a single entity, should I
implement it in the Entity, or in the
Service?

Yes, if it is behavior related to the entity then it should reside within the Entity. Entities shouldn't just be simple data containers, rather the Entity/Model layer should encapsulate both data-structure and behavior related to your business model. In this way, if you need to reuse the Model layer in another app, you dont have to dig around to find the related behavior that you stuck in other layers.

For example, if I have a post and want to retrieve all its comments that are approved, > should it be Post.getApprovedComments (entity) or > CommentsService.getApprovedCommentsForPost(Post post)?

Difficult to say without knowing more about your architecture and ORM. I'd probably go with the Post.. route (comments should be a collection on the Post entity), and then getApprovedComments could be a simple linq query or such. The Service based approach you suggest doesn't look very OOP to me.

(No, it's not right to use post.getComments().filter(c -> comment.approved), because that moves business logic out of the Model. Just in case someone asks.)

I'm not entirely sure I agree with you here. For something this simple, some might think it acceptable.

I'd add that:

Service (handles business logic like Get the 5 newest posts ordered alphabetically by title, uses the Repository)

...is in my opinion not a good example of a service. The service layer is doing nothing in this example - this should just be a query method defined in the PostRepository.

Hope some of that helps a little...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文