Automagically Load Class Files in PHP
If you have very much experience with writing medium/large PHP based projects, you've probably run into the following annoyance:
You have a bunch of classes that you use ubiquitously, some which you wrote and some which others have written. Each file has a single class in it, but since the classes are from difference sources, some of their files have non-consistent naming conventions. You have to include classes into the files which use them, so you might include all of the classes in a header file, but that will cause unnecessary overhead because even unneeded classes get included in ever file which uses the header at all. The other option is to individually include only the necessary classes into the files that use them, but what a pain in the ass!
Fortunately there is a third option, available in PHP 5.0+; it's called Autoloading Classes. Basically, as soon as an object of a class is created for which the source file has not yet been included a function called __autoload is called. Using that function, we can then include the appropriate class file just before the object is created. Thus avoiding including any additional classes via a header or having to type out extra includes. So how does this magical function work?
Here's a simple example from the PHP site:
function __autoload($class_name) {
require_once $class_name . '.php';
}Not bad, but rather restrictive. All it does is attempts to include a file called whateverYourClassIsCalled.php. If that file doesn't exist.. FATAL ERROR! Here is my version, which (at least to me) seems much more robust:
function __autoload($Name)
{
$seperators = array('.', '-', '', '_');
$namingConventions = array(
'class[SEP]'.$Name,
$Name.'[SEP]class',
$Name,
);
$includePath = array(
'/includes/',
'/secondary/path/'
);
foreach ($includePath as $path)
foreach ($seperators as $sep)
foreach ($namingConventions as $convention)
if (is_file($file = $_SERVER['DOCUMENT_ROOT'].$path.str_replace('[SEP]', $sep, $convention).'.php'))
include_once ($file);
}My function searches for any of the following files inside any pre-specified includes folder.
class.Example.php
Example.class.php
Example.php
class-Example.php
Example-class.php
Example.php
classExample.php
Exampleclass.php
Example.php
class_Example.php
Example_class.php
Example.php
Efficiency may take a small hit (a ten-thousandth of a second on my machine for each additional path) if you specify multiple include folders, but I think the ease of never having to specify your class files is well worth it. Also, it's worth noting that my function is completely case-insensitive, trust me on that one.


Last
Twitter
Myspace
Facebook
August 6th, 2010 - 01:27
UNNECESSARY! haha, thats pretty sweet now that I look at it completed.
August 6th, 2010 - 01:31
Congrats you are a dork