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.

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.

AMFPHP 1.0 Ready

AMFPHP (Flash Remoting written in PHP) has hit a stable version 1.0 release! I’ve been looking forward to this for a long time.

Flash Remoting is a method of transfering data to a Macromedia Flash Movie. It sends it in binary format and is much easier to use as it arrives in an object form, meaning, you don’t have to sort through the child nodes of an XML object. I have been using AMFPHP for over a year on several projects (being one of the main backend developers in my company, mediaRAIN) to send stuff. I created the logo storage of LogoMaker/InstaLogo using AMFPHP which handles, and I quote, “a lot.” Actaully, in July we got 4.4 million posts to the remoting service. I suppose that’s on average almost 100 a minute! We’ve also used remoting in several other applications.

I’ve been pretty pleased just with the ability to pass data back an forth from Flash to PHP. The only things that bothered me was the beastly methodTable array the PHP service needed and the design issue in which your Flash objects are converted into associative arrays in PHP rather than PHP objects. The methodTable is now created using reflecting and JavaDoc style documenting (very nice) and as for the array vs object issue, well, I made a hack for that myself in our version of the remoting. Associative arrays are “more natural” in PHP, and you can use the methodTable to define custom object types. Well, not recursively, however, you can now be able to associate a PHP class with a Flash class in version 1.0. Really nice feature. Kudos to all of those who have helped develop PHP remoting for Flash. You can see all of the new features in 1.0 yourself, but it’s faster, more organized, more features, and the whole bit.

Pherret currently can be integrated with Flash Remoting and will have full support as an extra module. mediaRAIN is all about Flash, so of course I had to take that into consideration as I built Pherret. But you have a truer Model View Controller (MVC) system when you can use different views (HTML or Flash) or controllers and the same model.

setProperties

One of the simple and very useful pieces of code in Pherret (a PHP 5 framework) is the setProperties() function in the base Object class. The name originally came from Java Beans and works in a similar manner. I’m sharing it because it could be used in any code with PHP 5 or PHP 4. First, here is the problem being solved. Do you ever find yourself setting and object (or array, or variables) from a HTTP post in the following manner?

 $user = new User(); $user->firstName = $_POST['firstName']; $user->lastName = $_POST['lastName']; $user->address = $_POST['address']; $user->city = $_POST['city']; $user->state = $_POST['state']; $user->zip = $_POST['zip']; $user->email = $_POST['email']; // validate the data $user->saveToDatabase(); 

Don’t you think it would be easier to do this?

 $user = new User(); $user->setProperties(); // validate data $user->saveToDatabase(); 

This can be done by having the User class extend the Object class. The Object class has a method called setProperties($params = $_REQUEST, $properties = '*', $prefix = '', $force = false) which by default sets all the properties that an extending object has from the $_REQUEST. There are many other ways you can use this method. You can set another source to populate your object from, including $_GET, $_POST, another array or even another object. You may also limit which properties are set by passing them into the $properties parameter in a comma delimited list. To set all properties you pass '*'. To set only some you would pass 'prop1, prop2, prop3.' If you want _all_ the properties set except one or two you may add a negative sign in front of the property like '*, -prop1, -prop2', '*' says use all, then the '-prop1,-prop2' would exclude those properties. In addition you may add a $prefix to the properties. This is useful if you have two objects and want to set both properties this way (ie. firstName, shipFirstName, billLastName). It takes care of the camel-case for you. And finally, there is the $force parameter. The default is false which means that only properties currently in the object will be set from items in the $params array/obj. By setting $force to true you may force all items to be set on the object. This is useful when you have an empty object, or one that has no class definition. Now, here is what you’ve been waiting for. The setProperties method to add to any class (or even better, any parent class).

 function setProperties($params = null, $properties = "*", $prefix = "", $force = false) { if (is_object($params)) { $params = get_object_vars($params); } elseif (empty($params)) { $params = $_REQUEST; } elseif (!is_array($params)) { //throw new Exception('The $params sent to setProperties is niether an object or an array (and it should be)'); return; } $props = explode(",", str_replace(" ", "", $properties)); $properties = array(); foreach ($props as $prop) { if ($prop == '*') { $properties = $force ? $params : get_object_vars($this); } elseif ($prop{0} == '-') { unset($properties[substr($prop, 1)]); } else { $properties[$prop] = 1; } } foreach ($properties as $prop => $value) { $prop = ($prop{0} == '_' ? substr($prop, 1) : $prop);
$param = empty($prefix) ? $prop : $prefix . ucfirst($prop); if (array_key_exists($param, $params)) { $setter = "set" . ucfirst($prop); $this->$setter($params[$param]); } } } function getProperties() { return get_object_vars($this); } 

I threw in the bonus getProperties() function :) I hope this can save at least one developer some repetative coding in their application.

« Previous Page