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

查看:224
本文介绍了胖模型,瘦控制器和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:


  • 胖模型,瘦的控制器

  • 在模型中保留尽可能多的业务逻辑

  • Fat models, skinny controllers
  • Keep as much business logic in the models as possible

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

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:


  • 应用程序具有包含项目的列表,并且可以对项目进行排名。

  • 类似地,项目(项目模型)也具有图像(图像模型)。每个项目可以具有默认图像(由项目表中的image_id指定)。当项目与其图像一起显示时,默认图像应首先显示。我有一个在控制器中执行此操作的逻辑。

  • 当显示列表时,相关列表显示在侧边栏中。确定哪些列表相关的逻辑在控制器中。

现在到我的问题:


  1. 根据上面给出的例子,我是在正确的轨道上,认为那些是属于模型的控制器中的逻辑的实例。


  2. 我确定识别这个问题并改变我的设计模式是一半战斗,但即使我决定采取我上面给出的那些例子,并试图将这个逻辑移动到一个模型,我不知道从哪里开始。任何人都可以通过在这里发布一些代码,或链接到一些好的学习资源,指向正确的方向? 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:


  1. Yes

任何处理数据或数据操作的操作都应该在模型中。在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天全站免登陆