MVC:将业务逻辑放在哪里? [英] MVC: Where to put business logic?

查看:38
本文介绍了MVC:将业务逻辑放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我看到了很多关于这个的问题,但背后的推理还不够.如果我的问题不够好应该删除我会理解的.

我看过,例如,this 和一个 45+ 投票的答案说他建议您将业务逻辑放在模型中,这听起来很合乎逻辑.

I have taken a look at, for example, this and a 45+ voted up answer says he advises you to put the business logic in the model, which sounds pretty logical.

然而,我的第一个大型项目我已经在控制器中完成了我所有的 BL,因为我没有质疑这些事情,而是在自动添加的 AccountController 中查看它是如何完成的如果您选择带有表单身份验证的 MVC.所有的方法看起来都充满了 BL.或者也许这是可以添加的最少量的代码而我忽略了一些东西?

However, my first large project I have done with all my BL fully in the controllers, because I didn't question these things and looked how it is done in the AccountController which is the automatically added if you choose MVC with form authentication. All the methods look pretty stuffed with BL. Or maybe it is the least amount of code that was possible to be added and I am overlooking things?

youtube 上的一个人问我他是否将所有逻辑都放入他的模型中,一开始我是错的!然后我开始想,也许他是对的!?

A person on youtube asked me whether he is right by putting all the logic into his models and at first I was no! Then I started thinking that maybe he was right!?

那么,毕竟,我应该把我的业务逻辑放在哪里?如果它在模型类中,那么,在控制器中的方法中,多少代码应该被认为是健康的?一行最多从控制器中的模型中调用一些方法然后返回到视图?

So, after all, where do I put my business logic? If it is in models classes, then, how much code should be considered a healthy amount in a method which is in controller? One line to call some method from the model in a controller at most and then a return to the view?

推荐答案

出于几个原因,我更喜欢将域逻辑放入模型中.

I prefer to put domain logic in the model for a couple of reasons.

  1. 模型中不应包含 UI 代码,因此更易于测试.只要有可能,我喜欢在编写任何 UI 代码之前有一个完全工作(意味着完整的测试覆盖)模型.控制器可以相信模型在做正确的事情并且只处理 UI 问题.

  1. The model should have no UI code in it and thus be easier to test. Whenever possible, I like to have a fully working (meaning complete test coverage) model before writing any UI code. The controller can trust that the model is doing the right thing and just deal with UI concerns.

如果您将域逻辑放在一个控制器中,那么在不同的应用程序之间,甚至在不同的控制器之间共享就不是那么容易了.

If you put domain logic in a controller, it's not as easy to share between different apps, or even between different controllers.

这篇关于MVC:将业务逻辑放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆