MVC Is Killing You MVC 是慢性谋杀

The biggest roadblock towards developers achieving good design is a simple acronym: M-V-C. Models, views, and controllers have dominated web framework thinking for years, in part because of the popularity of Ruby on Rails. However, ask a developer to define "model". Usually, you'll hear a few mutters and the word "database". Supposedly, the model is the database. It's where all your database stuff goes, whatever that means. But, as you quickly learn, your application needs a lot more logic than just a simple database access class. It needs to do validation, call external services, send e-mails, and more.

为了做出好的程序设计,最大的拦路虎就是一个简单的缩写词:M-V-C。模型、视图、控制器主宰了Web框架的思想已经好多年了。这种思想的流行某种程度上是托了 Ruby on Rails 愈加流行的福。然而,如果你问一个开发人员“模型”的定义是什么。通常你会听到他嘟哝着什么“数据库”之类的东西。这么说,模型就是数据库了。不管这意味着什么,模型里包含了关于数据库的一切。但是,你很快就会知道,你的应用程序需要的不仅仅是一个简单的数据库访问类。他需要更多的逻辑如:数据验证、调用外部服务、发送电子邮件,等等更多。

What Is A Model? 模型是啥?

The word "model" has become so ambiguous that it has no meaning. By developing with a more specific vocabulary, it will be easier to separate our application into smaller, cleaner classes with a clearly defined responsiblity.

单词 "model" 的含义太模糊了,很难说明白准确的含义。更具体来讲,模型是用来将我们的应用划分成更小、更清晰的类,使得各代码部分有着明确的权责。

So, what is the solution to this dilemma? Many developers start packing logic into their controllers. Once the controllers get large enough, they need to re-use business logic that is in other controllers. Instead of extracting the logic into another class, most developers mistakenly assume they need to call controllers from within other controllers. This pattern is typically called "HMVC". Unfortunately, this pattern often indicates poor application design, and controllers that are much too complicated.

所以怎么解决这个问题(译者注:上文中“更多的业务逻辑”)呢?很多开发者开始将业务逻辑包装到控制器里面。当控制器庞大到一定规模,他们将会需要重用业务逻辑。大部分开发人员没有将这些业务逻辑提取到别的类里面,而是错误的臆想他们需要在控制器里面调用别的控制器。这种模式通常被称为 “HMVC” 。不幸的是,这种模式通常也预示着糟糕的程序设计,并且控制器已经太复杂了。

HMVC (Usually) Indicates Poor Design HMVC(通常)预示着糟糕的设计。

Feel the need to call controllers from other controllers? This is often indicative of poor application design and too much business logic in your controllers. Extract the logic into a third class that can be injected into any controller.

你觉得需要在控制器里面调用其他的控制器?这通常预示着糟糕的程序设计并且你的控制器里面业务逻辑太多了。把业务逻辑抽出来放到一个新的类里面,这样你就可以在其他任何控制器里面调用了。

There is a better way to structure applications. We need to wash our minds clean of all we have been taught about models. In fact, let's just delete the model directory and start fresh!

有一种更好的程序结构。但首先我们要忘掉以往我们被灌输的关于“模型”的一切。干脆点,让我们直接删掉 model 目录,重新开始吧!

results matching ""

    No results matching ""