Tutorial? How About a Project!

In writing the articles on object oriented programming I have stuck with theory. After all, it is not language specific and takes less space to say what there is to say. However, I have been asked by serveral to provide a tutorial or include examples on object oriented code. Well, I’ve decided to do something more. My good friend Andrew Branch has pointed out many times before that we learn better when we do things ourselves. And so, in that spirit, we will start a new full-fledged project together. I will write along as we develope it about how we should try to do things, so we can more fully understand object oriented principles. And we can all write the code for it.

The Project

Going back to my roots, I learned to program by hacking on osCommerce code. I wanted to make my own ecommerce site and run my own buisness. It was then that I discovered how enjoyable programming was and stuck with that instead. The problem with osCommerce is, however, that it is very procedural. It has SQL queries inline with the HTML on it’s pages. It uses functions to output pixel images. It requires a lot of hacking to modify. It is an adequate example of what you might call “spaghetti code.”

ooCommerce

We will be starting a new open source project that will implement all the features of osCommerce, but in a better way. And hopefully, since this will be more extensable, we can add many new features. We can call this project ooCommerce for object oriented ecommerce. I have already purchased the domains oocomerce.com, .net, and .org so that we may, eventually, have our own site for it. And I have submitted it to Sourceforge for pending approval. The benchmark of features we will be aiming for is listed on osCommerce’s site. And, because we are going full out object oriented, we will be using PHP 5. I am sorry if you were hoping for PHP 4, but in order to teach better OOP principles, and because PHP 4 is such a hack in terms of OOP, that’s what we need to use.

I hope ooCommerce will be, if nothing else, a great learning experience. Instead of a little pointless tutorial on saying “hello world” in an object oriented manner, we will actually create a full-featured system as our tutorial, implementing all that we’ve learned previously. We will look at planning this project out next week, so stay tuned.

PHP Package Management and Autoloading

In PHP 5 and greater there is a magic function called __autoload (note: two underscores). __autoload allows us to load a class on the fly so to speak. It only gets called when a class can not be found, then it has a chance to load the class. If the class still can not be found, you get your regular error stating so. __autoload can be really useful if all of your classes happen to be in one directory, but what happens if you are managing a large project with many packages of classes? We will look at some different options.

Single Directory of Classes

This is the simplest solution, and the best if you have a small project. You may have situations where you would like to load the class without creating a new instance of it, so I will be creating a loadClass function in each example which __autoload will call. That way you may load a class manually. Here is what you might do if all of your classes are in one directory:

function __autoload($className) {
    loadClass($className);
}

function loadClass($className) {
    include_once('classes/' . $className . '.php');
}

Pretty Simple.

Packages of Classes

Now how about package management, with many directories of classes? A few developers have named their classes with the package names in the class name. For example, util_Parser would be the Parser class in the util directory (in your base classes directory), and util_html_HTMLParser would be the HTML parser class in the util.html package. Here is an example of how that would work:

function __autoload($className) {
    loadClass($className);
}

function loadClass($className) {
    include_once('classes/' . str_replace('_', '/', $className) . '.php');
}

Simple like the first method, but we get packages now. However, we have to actually name our classes with the package names in front of it. We start to get very long names for some of our classes. If we extended the Parser class we might have util_html_HTMLParser and util_xml_XMLParser or perhaps even deeper packages. We also find refactoring difficult because if a class must move to another package, we must go through all our code and rename the class everywhere we use it.

Package Management Using import

There is another way, although not as simple, which allows packages as deep as you would like, and requires minimal work when refactoring. This is the import way of doing things. import is a function which keeps track of what classes you might use in a certain script/class and then uses __autoload to look up the location of the class. Here’s how it works.

  • You import the class or package using the import function like this, import('util.html.HTMLParser');, at the top of your script
  • import stores the name of the class, ‘HTMLParser’, and the path to the class, ‘util/html/HTMLParser.php’, in a global associative array called imports
  • When the class is utilized, __autoload will do a lookup in the imports array for the class and load it in.

Here is how the code looks. It is a bit more complicated, but very nice to use for a larger system:

function __autoload($className) {
    loadClass($className);
}

function loadClass($className) {
    global $imports;
    if (isset($imports[$className])) {
        include_once($imports[$className]);
    }
}

$imports = array();
function import($import) {
    global $imports;

    // seperate import into a package and a class
    $lastDot = strrpos($import, '.');
    $class = $lastDot ? substr($import, $lastDot + 1) : $import;
    $package = substr($import, 0, $lastDot);

    // if this import has already happened, return true
    if (isset($imports[$class]) || isset($imports[$package.'.*'])) return true;

    // create a folder path out of the package name
    $folder = '' . ($package ? str_replace('.', '/', $package) : '');
    $file = "$folder/$class.php";

    // make sure the folder exists
    if (!file_exists($folder)) {
        $back = debug_backtrace();
        return trigger_error("There is no such package <strong>'$package'</strong> -- Checked folder <strong>'$folder'</strong><br />
            Imported from <strong>'{$back[0]['file']}'</strong> on line <strong>'{$back[0]['line']}'</strong><br />", E_USER_WARNING);
    } elseif ($class != '*' && !file_exists($file)) {
        $back = debug_backtrace();
        return trigger_error("There is no such Class <strong>'$import'</strong> -- Checked for file <strong>'$file'</strong><br />
            Imported from <strong>'{$back[0]['file']}'</strong> on line <strong>'{$back[0]['line']}'</strong><br />", E_USER_WARNING);
    }

    if ($class != '*') {
        // add the class and it's file location to the imports array
        $imports[$class] = $file;
    } else {
        // add all the classes from this package and their file location to the imports array
        // first log the fact that this whole package was alread imported
        $imports["$package.*"] = 1;
        $dir = opendir($folder);
        while (($file = readdir($dir)) !== false) {
            if (strrpos($file, '.php')) {
                $class = str_replace('.php', '', $file);
                // put it in the import array!
                $imports[$class] = "$folder/$file";
            }
        }
    }
}

There you have it. A powerful way to manage your packages and load only classes which are needed for use. Also, a feature of this method of autoloading classes is that you can use an asterisk, *, to import all the classes in a package. And it only loads the classes needed because of __autoload.

Finally, this is how you would use the import method in your scripts:

import('util.html.HTMLParser');
import('template.arras.*');

// here would be all of your important code
// not worrying about including files hwen you need them
// because you've already set it up to include them
// automatically when you use them, and only
// _if_ you use them
$p = new HTMLParser();
$t = new ArrasTemplate();
// etc.

Mint, Stat’s and Design

Mint is a new product recently released to track the statistics on your website. It has gotten much attention from several areas, and I thought it would be worth it to check it out.

I am currently using StatCounter.com to track the traffic to my site. It is really useful when you use their paid service which keeps track of more than the last 100 visits to your site (the free version cap). It lets you view all the regular stats as well as “drill down” to see the actual path a single visitor took through your site. But, it is a monthly subscription service, which means potenially hundreds of dollars a year, even though it’s not much each month.

Mint is a one-time site liscence fee of $30. So I felt it would be a good investment over the monthly fees of StatCounter. What sums up my thoughts upon using Mint is this: a regular stat tracker was given a great design and some cool javascript effects to make things easier to use. It looks wonderful, but it lacks much. Things such as tracking return visitors, displaying charts and graphs of the data, and being able to drill down to see individual users and their paths are things that really make a web stat tracker useful. A good user interface is important as well.

One bonus to Mint is it can be extendable with plugins or “pepper” as it’s called for marketing. Although, I’m not sure if extras will be sold by other developers, release for free even though the original is a paid product, or both. I should make it easier for the maker of mint to deploy new features anyway.

Overall, I enjoy Mint, and it’s price is much more favorable than the recurring price of StatCounter. I will stick with it and create some nice graphs of the data for my personal use (whenever I get spare time). Perhaps sell it as a plugin or something.

Dreamweaver and CSS Still Don’t Play Nice

After hearing about the new CSS based workflow of Dreamweaver 8, which came out yesterday evening, I had high hopes that the rendering engine for CSS and HTML would have been improved. Disappointingly, this wasn’t the case. Why don’t they try using the rendering engines for Firefox, Safari, and even IE. The first two are now completely open for use and the latter would be smart to include even if there is a liscencing fee. mediaRAIN, my employer, uses Macromedia Studio because we specialize in Flash products. However, we do many HTML/PHP projects as well. Dreamweaver has always been a favorite of mine with it’s HTML highlighting, code completion, and easy-to-use interface. I find myself more productive with Dreamweaver than with notepad. However, it would be really nice to use the WYSIWYG (Design View) to see my CSS styling as I create it rather than saving and viewing in the browser. There is no point in a WYSIWYG if what you see isn’t really what you get. To be fair, there are some really nice features with the new edition of Dreamweaver. There is code collapsing (which can collapse a selected section of code as well as an element). They’ve fixed the built in FTP client to work in the background. There is a more usable CSS panel which will show you all the styles applied to the currently selected element, even inherited ones. Their code completion is reworked and is a bit nicer. And you can turn on and off the underlining of invalid code (which actually doesn’t seem to work). My hope would be, in the future (near future would be nice), that Dreamweaver would add the ability of changing the WYSIWYG rendering engine to one of the three or four major browsers so that you can accuratly see what your CSS looks like in that browser. Either that, or fix their current renderer to properly display floating elements, absolutly positioned elements, and the correct box model.

Logout from HTTP Authorization

This is a little trick to create a logout from your site if you are using HTTP Authentication. I am using it for a current project I’m working on where cookie based sessions won’t reliably work. We (Derek Andriesian and I) are using HTTP Authenticaton to log into an account which is only accessed through javascript and image urls from other sites. Some browsers disallow cookies being set by sites other than the current one, so keepig the user logged in is not always possible using cookie-base session management.

To use HTTP Authentication you just do this in your PHP:

// retrieve the vars passed through HTTP Auth
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];

function login($user, $pass) {
    // check if this is a valid login and process necessary stuff
}

if (!$user || !$pass || !login($user, $pass)) {
    // send the headers which will popup the login dialog
    header( 'WWW-Authenticate: Basic realm="Private"' );
    header( 'HTTP/1.0 401 Unauthorized' );
    exit;
}
// logged in successfully

This works pretty good, however, there is no built in way to log a user out short of making them close their browser. But, you can “log them in” with a different username and password encoded into the link like so: http://username:[email protected]/page.php. So, it’s possible to create a logout page by sending them to a link http://x:[email protected]/logout.php. Then you may redirect them somewhere else, and as long as you don’t have a user with a username and password of ‘x’ and ‘x’ then they will be logged out of any valid account.

Another Product from Google

Google has just released Google Talk, an instant messaging and voice over IP client. It can be downloaded for free.

The download was incredibley small, especially when compared with MSN Messenger and similar services. Google Talk doesn’t have any adds or stupid features you never use. It’s small, light-weight, and fast.

One thing I would have liked is a feature where you could communicate with contacts that are using other services such as AIM, Yahoo IM, and MSN Messenger. But hopefully all my friends and family will use it soon so that I can get in touch with them through Google Talk instead.

Overall, I think it’s another great product from Google.

(See other Google products: Gmail, Google Maps, Google Earth. Also, I have some Gmail invites if others need)

« Previous Page — Next Page »