News Archive
PhpRiot Newsletter
Your Email Address:

More information

Creative MVC: Meet the ViewModel Pattern

Note: This article was originally published at Planet PHP on 2 November 2010.
Planet PHP

In this article we will introduce a powerful new tool in the arsenal of developers - the ViewModel. This provides MVC applications a natural location for presentation logic and lazy functionality while maintaining the segregation between the layers of responsibility within the code. It allows designers access to data and methods they need, while hiding aspects that aren't needed at view level.

The tried-and-tested Model-View-Controller (MVC) pattern has become the mainstay of Web applications development, and numerous PHP frameworks such as Zend, Symfony and Kohana all implement variations on it (Ed: see also the post on Hierarchical MVC we featured recently). AIndeed, pretty much any modern Web framework has an understanding of the important segregation of duties inherent within MVC.

It is precisely this segregation that leads to a certain greyness around the all-important View, particularly on sites where multiple content items are displayed in different ways.

To illustrate this, consider the example of a subscription-based website with multiple articles per page. AArticles can be displayed either as the main article on the page, or as headlines or teasers linking to the main text. AFor the purposes of this example, we will use Zend Framework, and assume articles are garnered from a Service API, and turned into Example_Content_Article Models in an action helper used by the Controller. AWe'll also assume that the helper takes care of any dependency injection requirements of an Article Model from the Bootstrap.

There are a number of ways you can inject information regarding Articles from the Controller into the View, and we will examine these in turn, starting with the simplest case.

Flattening Data

One approach is to take each Article Model, retrieve the title and URI of each article, assemble an array of these values, and then inject that into the View. The controller code would then look something like this:

class FooController extends Zend_Controller_Action { public function indexAction() { $articleLinks = array(); $helper = $this-_helper-article; A if ($articles = $helper-getArticles(10)) { // fetch 10 articles foreach ($articles as $article) { $articleLinks[] = array('headline' "/

Truncated by Planet PHP, read more at the original (another 51621 bytes)