MVC and the Zend Framework

In this four-part article series, you’ll learn about the model-view-controller (MVC) design architecture, why its use is a best practice when building web applications, and how using the Zend framework for PHP lets you make the most of this architecture. This article is excerpted from chapter 25 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).

Even at this likely early stage of your Web development career, chances are you’re already attempting to sketch out the features of a long-desired custom application. An e-commerce store perhaps? An online community forum devoted to stamp collecting? Or maybe something a tad less interesting but nonetheless very practical, such as a corporate intranet? Regardless of the purpose, you should always strive to base development around sound development practices, several of which have become increasingly well-defined over time. In fact, focus on this area has become such that several groups of developers have banded together to produce a variety of Web frameworks, each of which serves to help others develop Web applications in a manner thats efficient, rapid, and representative of sound development principles.

This chapter’s purpose is threefold. First, the case is made for why you should seek to embrace one of the most crucial of these best practices, known as the Model-View-Controller (MVC) design architecture. Second, several of the most popular PHP-driven frameworks are introduced, each of which allows you to take advantage of MVC, in addition to a variety of other time-saving features such as Ajax integration. We devote additional time to the Zend Framework, which although the newest of the bunch, is rapidly becoming the most popular of these framework solutions.

Introducing MVC

The advantages of the MVC architecture are perhaps best illustrated by providing an example of the problems that are sure to arise when it isn’t implemented. Suppose you’ve recently launched a new Web site, only to find it’s soon inundated with users. Eager to extend this newfound success, the project begins to grow in ambition and, as a result, in complexity. You’ve even begun to hire a few talented staff members to help out with the design and development. Well aware of your pathetic design skills, you’re particularly keen for the designers to immediately begin an overhaul that will lead to a relaunch next month. Accordingly, you ask them to begin redesigning all of the sites pages, many of which look like this:

    // Include site configuration details and page header

    // Scrub some data
$eid = htmlentities($_POST['eid']);

    // Retrieve desired employee’s contact information
$query = "SELECT last_name, email, tel
FROM employees
WHERE employee_id=’$eid’";

    // Parse and execute the query
    $stmt = oci_parse($conn, $query);

    // Convert result row into variables
    list($name, $email, $telephone) = oci_fetch_array($stmt, OCI_NUM);

<div id="header">Contact Information for: <?php echo $name; ?></div>
Employee Name: <?php echo $name; ?><br />
Email: <?php echo $email; ?><br />
Telephone: <?php echo $telephone; ?><br />

<div id="sectionheader">Recent Absences</div>

    // Retrieve employee absences in order according to descending date
    $query = "SELECT absence_date, reason
              FROM absences WHERE employee_id=’$eid’
              ORDER BY absence_date DESC"

    // Parse and execute the query
    $stmt = oci_parse($conn, $query);

    // Output retrieved absence information
    while (list($date, $reason) = oci_fetch_array($stmt, OCI_NUM)) {
        echo "$date: $reason";

    // Include page footer
    INCLUDE "";


Because the design and logic are inextricably intertwined, several problems soon arise:

  1. Designers who were hired with the sole purpose of making your Web site look great are now distracted by the task of having to learn PHP. 
  2. Developers who were hired to help out with the expansion of Web site features are now distracted by fixing the bugs and security problems introduced by the novice PHP code written by the designers. In the process, they decide to make their own little tweaks to the site design, infuriating the designers. 
  3. Although a proper code versioning system has been deployed, the almost constant conflicts that arise due to simultaneous editing of the same set of files soon become tiresome and time consuming.

You’re probably noticing a pattern here: the lack of separation of concerns is breeding an environment of pain, distrust, and inefficiency. But there is a solution that can go a long way toward alleviating these issues: the MVC architecture.

The MVC approach renders development more efficient by breaking the application into three distinct components: the model, the view, and the controller. Doing so allows for each component to be created and maintained in isolation, thereby minimizing the residual effects otherwise incurred should the components be intertwined in a manner similar to that illustrated in the previous example. While rather detailed definitions of each component exist in other learning resources, for the purposes of this introduction the following will suffice:

  1. The model: The model defines the rules for the world or the process an application is intended to represent. You can think of it as the specification responsible for both the application’s data and the behavior. For instance, suppose you create an application that serves as a conversion calculator, allowing users to convert from pounds to kilograms, feet to miles, and Fahrenheit to Celsius, among other units. The model is responsible for defining the formulas used to perform such conversions, and when presented with a value and desired conversion scenario, will carry out the conversion and return the result. Note it is not responsible for formatting the data or presenting it to the user. This is handled by the view. 
  2. The view: The view is responsible for formatting the data returned by the model and presenting it to the user. It’s possible for more than one view to utilize the same model, depending on how the data should be presented. For instance, you might offer two interfaces for the conversion application: a Web-based interface, in addition to one created using PHP-GTK (http:// 
  3. The controller: The controller is responsible for determining how the application should respond based on events occurring within the application space (typically user actions), done by coordinating with both the model and the view to produce the appropriate response. A special controller known as a front controller is responsible for routing all requests to the appropriate controller and returning the response.

To help you better understand the dynamics of an MVC-driven framework, let’s work through a typical scenario involving the converter application, highlighting the role of each MVC component:

  1. The user desires the application to perform an action, for instance, converting an input temperature from Fahrenheit to Celsius. The user then submits the form by clicking a submit button.
  2. The controller responds by identifying the appropriate action, gathering the input, and supplying it to the model.
  3. The model executes the function responsible for converting Fahrenheit to Celsius and returns the calculated value to the controller.
  4. The controller calls the appropriate view, passing along the calculated value. The view is rendered and returned to the user.

The next section introduces four PHP-driven frameworks, each offering its own similar but unique MVC implementations.

{mospagebreak title=PHP’s Framework Solutions}

While PHP has long been perfectly suited for development the MVC way, no widespread solutions emerged until the wild success of Ruby on Rails ( seemingly turned the spotlight away from the language long known as the reigning king of Web development. Thankfully, PHP enthusiasts are practical folks and borrowed heavily from the compelling features espoused by not only Rails but also many other MVC frameworks. The following list highlights four of the more prominent PHP-specific solutions.

Note  You’ll also find that each of the frameworks introduced in this section has significantly more to offer than an MVC implementation. For instance, each facilitates Ajax integration, input filtering, and database interaction. You’re encouraged to carefully investigate the unique features of each in order to determine which best fits the needs of your particular application.   

The CakePHP Framework

Of the four solutions described in this section, CakePHP ( most closely corresponds to Rails, and indeed its developers readily mention the project was originally inspired by the breakout framework. Created by Michal Tatarynowicz in 2005, the project has since attracted the interest of hundreds of active developers and has even led to the founding of the nonprofit Cake Software Foundation ( and CakeForge (, a community repository for hosting Cake-driven projects, plug-ins, and applications.

The CakeForge initiative is showing considerable success, with 100 hosted projects and more than 2,100 registered users at the time of publication. Interesting projects include BakeSale, a Cake-driven shopping cart and catalog system, Cheesecake Photoblog, a customizable photoblog, and CakeAMFPHP, a Cake- and Flash-driven bulletin board.

Note  Unlike the three solutions that follow, Cake is capable of running on both PHP 4 and 5, meaning users faced with hosting providers who’ve yet to upgrade to version 5 still have an opportunity to take advantage of a powerful PHP framework.   

The Solar Framework

Solar (, an acronym for simple object library and application repository for PHP 5, offers an extraordinary number of classes for facilitating rapid application development. Founded and led by Paul M. Jones, who is also responsible for several other major PHP projects, including the Savant Template System (, DB_Table (, Text_Wiki (, and Yawp (, Solar benefits from both the experience gained and lessons learned from Jones’s active involvement in building other popular development solutions. Text-to-XHTML conversion, role management through a variety of mechanisms (file-based, LDAP, SQL), multiple authorization mechanisms (.ini files, htpasswd, IMAP, LDAP, and others), and interesting features such as social bookmarking components are just a few of the capabilities Solar has to offer.

The symfony Framework

The symfony framework ( is the brainchild of Franois Zaninotto, founder of the French Web development firm Sensio ( What’s unique about symfony is it’s built atop several other mature open source solutions, including the database abstraction layer Creole (, the Mojavi MVC layer (, and the Propel ( object-relational mapping layer. By eliminating the additional development time otherwise incurred in creating these components, symfony’s developers have been able to focus on creating features that greatly speed up application development time. Users of symfony can take advantage of automated forms validation, pagination, shopping cart management, and Ajax interaction using Prototype (

Note To learn more about the symfony framework, consult the fantastic documentation found on the project Web site ( Also, check out The Definitive Guide to symfony by project founder Fabien Potencier and project documentation leader Franois Zaninotto (Apress, 2007).

All three of the aforementioned frameworks are extremely capable and prominent solutions used by countless developers around the globe. There is however another solution that is showing considerable promise, and accordingly is given special attention in this chapter.

Please check back next week for the continuation of this article.

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan