The Awesomeness of PHP __autoload

Many of you have probably written or at least tried to write a PHP framework at some point during your career. The best way to write a frameworks, in my very humble opinion, is to use object oriented programming (OOP) and a sort of model/view/controller (MVC) architecture. In most cases this means that by the end of writing a sort of usable system you will have a large amount of files filled with different bits of code.

In the bad old days before PHP 5 you would have an index.php file and that looked something like this:

<?php
/**
 * Index file of Xframework.
 */

// Include all sorts of useful stuff...
include_once '/tag/framework/bootstrap.html';
include_once '/app/model/x.class.html';
include_once '/app/model/theme.class.html';
include_once '/app/controller/user.class.html';
include_once '/app/view/index.html';

// Now we can finally do something.
$x = new x();
$x->run();

Wouldn’t it be really nice if we could just write the code without having to worry about including millions of files everywhere, which can become a pain in terms of maintainability.

Enter __autoload() in PHP5. YAY! All our troubles magically disappear. Well not really, but your life is made slightly easier. So instead of the above, you now have:

<?php
/**
 * Improved index file of Xframework.
 */

// Our pretty __autoload() function.
function __autoload($classname) {
  include_once '/app/classes/'. $classname .'/tag/framework/.html';
}

// Run the framework.
$x = new x_controller();
$x->run();

Using __autoload should theoretically also improve the speed at which your app loads because you only load the files that are needed at the time.

You could also do some really complex configurations like the below for example:

<?php
/**
 * A more complex __autoload example for Xframework.
 */

// Autoload some classes.
function __autoload($classname) {
  $class = explode('_'. $classname);

  $class_file = $class[0] .'/tag/framework/.html';
  $class_type = $class[1];

  // Include the class.
  include_once '/app/'. $class_type .'/index.html'. #class_file;
}

// Let's run the app.
$x = new x_controller();
$x->run();

In the example above the autoload function is checking the class name for a type. The type could be, for example, model, view, controller, elephant or whatever you wanted it to be. That type is the directory where the class is stored. In the example we called the x_controller class. So that class would be located at /app/controller/x.php, the same would be true if you wanted it to be x_model or x_view.

This most definitely makes my life easier when I write PHP applications. If you spend a lot of time writing PHP applications and don’t use a specific framework for the job I would suggest that you put together a rough toolkit for yourself using __autoload() as the heart.