重构 MVC 控制器代码。控制器或型号
我的控制器中有很多代码,但我不确定将其放在哪里。首先,我对其进行了重构,使其干燥但仍在控制器中。
重构代码时要遵循什么好的准则,例如何时将某些内容移动到模型以及何时将某些内容保留在控制器中?
I have a lot of code in a controller and I'm not sure where to put it. First I re-factored it so that it is DRY but still in the controller.
What is a good guideline to follow when re-factoring code, such as when to move something to a model and when to keep something in a controller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的模型通常不应包含任何业务逻辑。如果是,则将该模型提取到 ViewModel 中,其中唯一的逻辑应该是与显示相关的代码。任何业务方法都应该存在于单独的类中。有些人喜欢一直使用
ViewModels
而不是一般的整体模型(例如CustomerEditViewModel
而不仅仅是Customer 模型
)。控制器应该非常轻量级,并且其中不应包含数据访问代码。我通常调用存储库方法(存储库模式)来轻松加载数据和 外观模式作为执行任何业务方法的网关。
例如,可以将这些全部放入一个外观类中,该外观类采用模型或
customerId
并执行以下操作,而不是使用数据加载代码、一些计算和一些保存代码:您的存储库类通常是编码到接口;这使得存根/模拟这些类以加载“假”数据变得非常容易,并且还将控制器和外观从直接链接到类的具体实现而不是链接到接口中分离出来。
Your model generally should contain no business logic. If it does, extract that model out into a
ViewModel
and the only logic in it should be your display related code. Any business methods should exist in a separate class. Some prefer to useViewModels
all the time instead of general overall models (ex.CustomerEditViewModel
instead of just aCustomer model
).The controller should be very lightweight and should not have data access code in it. I generally call a repository method (Repository Pattern) to easily load data and the Facade Pattern as a gateway to any business methods that are performed.
For instance, rather than having data loading code, some calculations, and some saving code, this could all be put into a facade class that takes a model or
customerId
and does something like:Your repository class is usually coded to an interface; this makes stubbing out/mocking these classes to load 'fake' data extremely easy and also decouples your controller and facade from linking directly to a concrete implementation of a class, but instead to an interface.
控制器应主要包含协调代码。因此,如果有机会,您有执行某些业务或域功能的代码,您可以将其移动。我倾向于使用应用程序服务或简单的任务。像 IImageService 或 IDocumentService 之类的东西(尽管实现可能变得相当臃肿)。我也喜欢使用单独的任务,例如 ILoginTask。
然后注入实现(我使用 Castle Windsor 和自定义控制器工厂)。
只是我的 2c --- HTH
The controller should primarily contain coordination code. So if, by some chance, you have code performing some business or domain function you could move that. I tend to use application services or simple tasks. Something like IImageService or IDocumentService (although the implementations can become quite bloated). I also like using individual tasks such as ILoginTask.
The implementations are then injected (I use Castle Windsor with a custom controller factory).
Just my 2c --- HTH