Understanding MVC in PHP

by Joe Stump
09/15/2005
Add Tag Clouds to Your Site

This article series (continued in Implementing MVC in PHP: The Controller, Implementing MVC in PHP: The View, and Implementing MVC in PHP: The Model) demonstrates how to build an MVC web framework using PHP 5. This article covers the basics of MVC web frameworks, building the foundation classes for a framework that the other three articles in this series will build.

With the introduction of PHP 5 and its new OOP features developers can now seriously talk about building solid APIs and more complex MVC frameworks for the web in PHP. This was possible before, but the new features in PHP 5 make it easier to integrate more advanced features into MVC frameworks, such as SOAP and WSDL.

In this article I assume that you have a solid understanding of object-oriented programming and that you have at least scanned the upcoming changes to the OOP structure of PHP in PHP5.

What is MVC?

MVC is the idea that you have three different pieces that work in unison to form a complex application. A car is a good real-world example of MVC. With a car you have two views: the interior and the exterior. Both take input from the controller: the driver. The brakes, steering wheel and other controls represent the model: they take input from the controller (driver) and hand them off to the views (interior/exterior) for presentation.

MVC on the Web

The ideas behind MVC frameworks are quite simple and extremely flexible. The idea is that you have a single controller (such as index.php) that controls the launch of applications within the framework based on arguments in the request. This usually includes, at a minimum, an argument defining which model to invoke, an event, and the usual GET arguments. From there the controller validates the request (authentication, valid model, request sanitization, etc.) and runs the requested event.

For instance, a request for /index.php?module=foo&event=bar might load a class called foo and run foo::bar(). The advantages of this method include:

  • A single entry point for all applications.
  • Removing the headaches involved with maintaining numerous scripts, each with their own relative paths, database connections, authentication, etc.
  • Allowing the consolidation and reuse of code.

Why Create My Own MVC Framework?

This article doesn't really advocate "You should write your own MVC web framework!" as is tries to explain "This is how MVC web frameworks work in theory, and why they are so great."

As of this writing, there are very few true MVC frameworks written in PHP. In fact, there is only one that I know of, Solar, that is entirely pure PHP 5 code. Another one out there is Cake, which is trying to be the "Ruby on Rails of PHP." I, personally, have a few problems with both of these frameworks. Both Solar and Cake fail to leverage existing code in PEAR, Smarty, etc. Cake appears a bit disorganized at the moment. Finally, Solar is the work of mostly a single person (not that Paul isn't a great coder or person, but there is only a single gatekeeper at the time of this writing). These may not be issues that concern you, and if they don't concern you, by all means check these two out.

The Old Way

If I could go back in time and look at code I wrote in early 2001, I would find a file called template.txt that looked something like:

<?php

require_once('config.php'); // Other requires, DB info, etc.

$APP_DB = 'mydb';
$APP_REQUIRE_LOGIN = false; // Set to true if script requires login
$APP_TEMPLATE_FILE = 'foo.php'; // Smarty template
$APP_TITLE = 'My Application';

if ($APP_REQUIRE_LOGIN == true) {
    if (!isset($_SESSION['userID'])) {
        header("Location: /path/to/login.php");
        exit();
    }
}

$db = DB::connect('mysql://'.$DB_USER.':'.$DB_PASS.'@localhost/'.$APP_DB);
if (!PEAR::isError($db)) {
    $db->setFetchMode(DB_FETCHMODE_ASSOC);
} else {
    die($db->getMessage());
}

// Put your logic here

// Output the template
include_once(APP_TEMPLATE_PATH.'/header.php');
include_once(APP_TEMPLATE_PATH.'/'.$APP_TEMPLATE_FILE);
include_once(APP_TEMPLATE_PATH.'/footer.php');

?>

Oh man, just looking at this code makes me cringe now. The idea with this approach was that every application fit into this set approach and I could just copy template.txt to myapp.php, change some of the variables, and then voila, it would work. However, this top-down approach has some serious flaws.

  1. What if my boss wanted me to change myapp.php to output a PDF in some cases, HTML in others, and SOAP if the request posted XML directly?
  2. What if this app required IMAP or LDAP authentication?
  3. How would I go about handling various modes in the script (including edit, update, and delete)?
  4. How would I handle multi-level authentication (admin versus non-admin)?
  5. How would I turn on output caching?
Building Tag Clouds in Perl and PHP

Essential Reading

Building Tag Clouds in Perl and PHP
By Jim Bumgardner

Tag clouds are everywhere on the web these days. First popularized by the web sites Flickr, Technorati, and del.icio.us, these amorphous clumps of words now appear on a slew of web sites as visual evidence of their membership in the elite corps of "Web 2.0." This PDF analyzes what is and isn't a tag cloud, offers design tips for using them effectively, and then goes on to show how to collect tags and display them in the tag cloud format. Scripts are provided in Perl and PHP.

Yes, some have said tag clouds are a fad. But as you will see, tag clouds, when used properly, have real merits. More importantly, the skills you learn in making your own tag clouds enable you to make other interesting kinds of interfaces that will outlast the mercurial fads of this year or the next.


Read Online--Safari
Search this book on Safari:
 

Code Fragments only

Pages: 1, 2, 3, 4, 5, 6

Next Pagearrow