Over a million developers have joined DZone.

Ajax and MVC

· Web Dev Zone

These two buzzwords have emerged in the last years as key features of frameworks, both in the PHP landscape and in other languages' niches. Let's analyze what is the relationship between Ajax technology and MVC frameworks, and why they are so comfortable with each other.

MVC

The Model-View-Controller pattern separates every feature of an application into three aspects: the Model, which is the representation of data and domain-specific behavior; the View(s), which reflects the changes to the model and handled the presentation logic; and the Controller which channels the user actions to drive the Model. The goal of this separation of concerns is being able to change as much as possible of one of the three layers without having an impact on each of the others.

Many web frameworks have embraced the MVC pattern, introducing a stack of components for Controllers and Views (and in some cases also to ease the development of the Model) to subclass or configure in order to build a full-featured web application without handling the raw HTTP requests. In the case of PHP, frameworks abstract away much of the boilerplate work with the native language constructs ($_GET, $_POST, $_SESSION), and provide an higher-level object-oriented Api.

AJAX

The introduction of the XMLHttpRequest object in modern browsers marked the starting point of the AJAX (Asynchronous JavaScript And XML) era, where a page is capable of initiating HTTP requests towards the server-side application following events that happen on the client. The initial innovation leaded the way for the diffusion of javascript libraries that performed reliable cross-browser Ajax request for the first time, and were able to compose pages from segments generated independently on the server, inserting them in the DOM.

Although the AJAX acronym comprehends XML, anything can be returned from such a server request for the client's pleasure, from text to HTML to Json. AJAX is everywhere now: Twitter and Facebook timelines are realized by inserting AJAX results into the homepage, and DZone infinite pagination is implemented with the same pattern. Google's GMail and Google Documents makes heavy use of AJAX. A modern application cannot ignore the revolution that AJAX brought to web development.

Their union

While the MVC pattern is not inherently web-related, the AJAX technology takes advantage of the separation of concerns favored by MVC to reuse as much code as possible on the server, and enrich the user experience. How does AJAX affects the classical MVC components of a web application?

The Model component is usually not touched when introducing AJAX into an application as it deals with the inner business logic of the application. If the Model itself is well factored, it will continue to reside on the server and ignores every change in the presentation layer which derives from AJAX-powered web pages.

The View becomes instead the principal subject of changes, as AJAX pages are essentially different implementations of the Views, that still are the target of of the same Model. Here are two simple examples of alternate Views used as AJAX callbacks:

  • a View can be generated without layout (header, footer, menus), for the inclusion of it as a simulated frame into an already existing page. Historically, this was one of the first and simplest implementation of AJAX-powered webpages, which would modify a specific div instead of reloading the whole document. The AjaxLink jQuery plugin is an example of this application.
  • a View can return part of the Model, like a single object or a collection, in a different format from the human-readable html. Examples of machine-readable formats are representations as XML, Json, or literal JavaScript.

The Controller layer still reacts to HTTP requests as the basic event generated from the client, although most of the requests are not focused on a complete document, but more on a particular endpoint or resource. Of course, these resources are virtual as much as the original documents, since this is the dynamic nature of a web application.

The controller has to return the appropriate View of the Model as a text stream (this is a requirement from the format of HTTP responses), which as seen before are different formats of the same object graph. Part of the Controller is moved on the client: while Views were produced on the server and rendered on the client from the start, the boundary is not clearly defined in AJAX applications.

For example, when a View in Json or XML format is returned to the client, this is an intermediate representation as the View that the end user will ultimately see is always composed by segments of HTML code. So we have what for the server-side architecture is only a View becoming input for a Controller on the client, which generates or clones HTML to accomodate it.

The original View and the client-side Controller may not even be part of the same application, as the latter may consume an external web service. Though, there are security limitations in what an XMLHttpRequest object can do, thus these mashups have either to pass from the server or to use an hidden iframe as a proxy (the same workaround commonly used for AJAX-like file uploads).

Support

How frameworks embrace AJAX and what support is provided to further extend the MVC metaphor into AJAX applications? Having tried Zend Framework for managing the multiple-format Views I talked about earlier, I saw that the generic PHP code is already present and ready to be employed.

The Zend_Controller component provide an helper named AjaxContext, which is configured while subclassing the base controller of the MVC stack. The configuration sets up specific actions for usage with XMLHttpRequest calls, by letting the helper intercept the requests. It recognizes the X-Requested-With non-standard HTTP header sent from most of the javascript libraries and disable the standard layout, switching the view to render (a PHP script in Zend Framework) from action.phtml to action.xml.phtml or even to json_encode().

With this example in mind, it's very easy to extend an existing application by introducing AJAX user experiences, while reusing the existing code. The separation of concerns of MVC is finally leveraged: the Model does not change at all, the controllers are tweaked and separate implementations of the Views are coded.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}