胖模型、瘦控制器和 MVC 设计模式 [英] Fat models, skinny controllers and the MVC design pattern

查看:23
本文介绍了胖模型、瘦控制器和 MVC 设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了一篇博文 用银行类比来解释 MVC.我在使用 MVC 框架 (CakePHP) 进行 Web 应用程序开发方面有几个月的经验,所以我掌握了基础知识,但我开始看到一个主题,这让我觉得我在放置逻辑时采用了一种有缺陷的方法:

I just read a blog post that explains MVC with a banking analogy. I have a few months of experience with web application development with an MVC framework (CakePHP), so I get the basics, but I began to see a theme that made me think I'm taking a flawed approach to where I put my logic:

  • 胖模型,瘦控制器
  • 在模型中保留尽可能多的业务逻辑

在我的应用中,模型是厌食症而控制器是肥胖的.我在控制器中有所有业务逻辑,除了模型中的关联和验证规则之外什么都没有.

In my app, models are anorexic and controllers are obese. I have all business logic in the controllers and nothing besides associations and validation rules in the models.

扫描我的控制器,我现在可以确定模型中可能应该包含的许多逻辑:

Scanning through my controllers, I can now identify a lot of logic that should probably go in a model:

  • 该应用程序具有列表,其中包含项目,并且项目可以排名.将列表按顺序排列的排序逻辑在控制器中.
  • 同样,物品(Item model)也有图片(Image model).每个项目可能有一个默认图像(由项目表中的 image_id 指定).当一个项目与其图像一起显示时,默认图像应该首先出现.我有在控制器中执行此操作的逻辑.
  • 显示列表时,侧边栏中会显示相关列表.确定哪些列表相关的逻辑在控制器中.

现在我的问题:

  1. 根据我上面给出的示例,我是否认为这些是当前属于模型的控制器中的逻辑实例?
  2. 还有哪些其他逻辑领域(网络应用常见)应该纳入模型?
  3. 我确信确定这个问题并改变我的设计模式是成功的一半,但即使我决定采用上面给出的那些例子并尝试将该逻辑移到模型中,我也不知道从哪里开始.任何人都可以通过在此处发布一些代码或链接到一些好的学习资源来为我指明正确的方向吗?CakePHP 的特定帮助会很棒,但我相信任何 MVC 都足够了.

推荐答案

给你正确"的答案有点困难,因为其中一些涉及框架的细节(无论你使用的是哪个框架)).

It's a bit tough to give you the "right" answers, since some of them deal with the specifics of the framework (regardless of the ones you are working with).

至少在 CakePHP 方面:

At least in terms of CakePHP:

任何处理数据或数据操作的东西都应该在模型中.就 CakePHP 而言,简单的 find() 方法怎么样?...如果它有机会做一些特殊"的事情(即回忆一组特定的条件"),而您在其他地方可能需要这些,那么这是包装在模型方法中的一个很好的借口.

Anything that deals with data or data manipulation should be in a model. In terms of CakePHP what about a simple find() method? ... If there is a chance that it will do something "special" (i.e. recall a specific set of 'condition'), which you might need elsewhere, that's a good excuse to wrap inside a model's method.

不幸的是,从来没有一个简单的答案,代码的重构是一个自然的过程.有时你只是醒来:神圣的通心粉......应该在模型中!"(好吧,也许你不这样做,但我有:))

Unfortunately there is never an easy answer, and refactoring of the code is a natural process. Sometimes you just wake up an go: "holy macaroni... that should be in the model!" (well maybe you don't do that, but I have :))

这篇关于胖模型、瘦控制器和 MVC 设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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