胖模型,瘦控制器和 MVC 设计模式

我刚读了一篇用银行类比解释 MVC 的 博客文章文章。我有几个月的使用 MVC 框架(CakePHP)开发 web 应用程序的经验,所以我得到了一些基础知识,但是我开始看到一个主题,这个主题让我觉得我把我的逻辑放在了一个有缺陷的地方:

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

在我的应用程序中,模特是厌食症患者,控制器是肥胖者。我在控制器中拥有所有的业务逻辑,除了模型中的关联和验证规则之外,没有其他任何东西。

通过浏览我的控制器,我现在可以识别出一个模型中可能应该包含的许多逻辑:

  • 该应用程序有包含项目的列表,并且可以对项目进行排序。将列表按排序顺序排列的排序逻辑位于控制器中。
  • 类似地,项目(项目模型)也有图像(图像模型)。每个项目可以有一个默认映像(在项目表中由 image _ id 指定)。当一个项目与其图像一起显示时,默认图像应该首先出现。我有在控制器中做这件事的逻辑。
  • 当显示一个列表时,相关的列表将显示在侧边栏中。确定哪些列表相关的逻辑在控制器中。

现在回到我的问题:

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

I'm using at least these two 'tests' to check if my logic is in the right place:

1) If I write a unittest, is is easy to only create the one 'real' object to do the test on (= the object that you are using in production) and not include lots of others, except for maybe some value objects. Needing both an actual model object and an actual controller object to do a test could be a signal you need to move functionality.

2) Ask myself the question: what if I added another way to use these classes, would I need to duplicate functionality in a way that is nearly copy-paste? ... That's also probably a good reason to move that functionality.

also interesting: http://www.martinfowler.com/bliki/AnemicDomainModel.html

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).

At least in terms of CakePHP:

  1. Yes

  2. 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.

  3. 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 :))