last update: 2009-05-01 04:55:14 GMT This book is a work in progress; feel free to contribute.
MVC is an acronym that stands for Model, View, Controller. It describes a form of web-application structuring that is easy to test and maintain because it separates business logic, server logic, and content generation. This is the structure of the standard Merb app that is generated by the ’merb-gen app’ command. It is also the structure used by Rails, CakePHP, Django, and many other popular web-development frameworks.
To develop in Merb effectively, it is important that one understands both how the MVC structure works, and the most effective way to work with it. This chapter will discuss the overall framework; the following three chapters will look at each piece in detail.
Models are the core of the framework. They are responsible for the business logic of your application; in Merb, they are most often associated with database access through an ORM such as DataMapper or Active Record. Sometimes models are used with an ORM, as nothing more than a wrapper for a database table. However, it is generally considered a best practice to have ‘fat’ models. That means the model classes are where you should keep things such as data relationships and methods for any non-trivial piece of data retrieval or manipulation. Models are the core of the framework. They are responsible for the business logic of your application. In Merb, they are most often associated with database access through an ORM such as DataMapper or ActiveRecord.
Views are the glitzy outer shell of an application. Views are responsible for generating the actual content (HTML, XML, JSON) returned by a request. Most commonly, views are written in a templating format such as Erb (embedded Ruby) or Haml. Wise developers will attempt to put as little code as possible into their Views.
Controllers deal with taking an incoming request and turning it into a response. They are responsible for interpreting the incoming request, getting instances of the needed Models, and passing this information along to the View.
In the default Merb application, the code for all three of these pieces is found in folders of the same name under the ’app’ directory. In the next chapters, we will look at how Merb implements each of these parts.
Novice users are often tempted to add lots of code into the controller layer, but this leads to code that is brittle and hard to test. Instead, developers are well advised to keep their controllers as ‘skinny’ as possible by pushing code that does not directly relate to the request/response cycle (or the gathering of data) into the Model.