首页 > PHP编程 > From Apprentice To Artisan 翻译 10

From Apprentice To Artisan 翻译 10


From Apprentice To Artisan 翻译 10


Application Structure 应用结构

Introduction 介绍

Where does this class belong? This question is extremely common when building applications on a framework. Many developers ask this question because they have been told that “Model” means “Database”. So, developers have their controllers that interact with HTTP, models which do something with the database, and views which contain their HTML. But, what about classes that send e-mail? What about classes that validate data? What about classes that call an API to gather information? In this chapter, we’ll cover good application structure in the Laravel framework and break down some of the common mental roadblocks that hold developers back from good design.


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.


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 (Usually) Indicates Poor Design


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!


分类: PHP编程 标签: