Wednesday, February 14, 2007

WK5 - Model-View-Controller (MVC) applying to AJAX;

Model-View-Controller (MVC) is a way of describing a good separation between the part of a program that interacts with a user and the part that does the heavy lifting, number crunching, or other "business end" of the application.

The MVC pattern identifies three roles that a component in the system can fulfill.

The Model is the representation of the application's problem domain, the thing that it is there to work with. For example, a word processor would model a document; a mapping application would model points on a grid, contour lines, and so on.

The View is the part of the program that presents things to the user- input forms, pictures, text or widgets. The view need not be graphical. In a voice-driven program, for example, the spoken prompts are the View.

The golden rule of MVC is that the View and the Model shouldn't talk to each other. Taken at face value, that might sound like a pretty dysfunctional program, but this is where the Controller comes in. When the user presses a button or fills in a form, the View tells the Controller. The Controller then manipulates the Model and decides whether the changes in the Model require an update of the View, it tells the View how to change itself.

The advantage of this is that the Model and View remain loosely coupled, that is, neither has a deep understanding of the other. Obviously they need to enough to get the job done, but the View knows about the Model only in very general terms.

Come back to AJAX and look at Figure 3.8. The Model is our collection of domain objects, persisted to the database automatically using our ORM (Object Relational Mapping). The View is the template defining the XML format. The Controller is to glue the Model and the View together. In web server tier of AJAX application which serves XML documents.

Although different design pattern we work with, the principle is the same. For some instances, J2EE enterprise beans abstract the Model and Controller to the point where they can reside on different servers. .NET "code-behind" classes delegate the Controller role to page-specific objects, whereas frameworks such as Struts define a "front controller" that intercepts and routes all request to the application. Framework such as Apache Struts have works this down to a fine art, refining the role of the Controller to route the user between pages, as well as applying at the single-page level. (In an AJAX application, we might do this in the JavaScript.) But in all cases, the mapping is basically the same, and this is how MVC is generally understood in the web application world.

Describing our web architecture using MVC is useful approach, and it will continue to serve us well as we move from classic to AJAX-style application. But it isn't the only use to which we can put MVC in AJAX.

Reference:

No comments: