Posted by : Chris London in (Programming, Tutorial)

Organizing PHP Includes with Autoload

Tagged Under : , , , ,

Since PHP5 was released, PHP programmers have been blessed with a decent support of object-oriented programming. With this ability many programmers have used classes in many if not all of their projects. A very common practice for OO programmers is to place each class in an includes folder. There have been many times when I have seen a config file full of includes and/or requires. They will include every class in their includes folder whether or not they use it in a particular script. This causes many unnecessary includes.

Their code may look something like:

<?php
   require('classes/Main.php');
   require('classes/AuthMain.php');
   require('classes/AuthUser.php');
   require('classes/UtilEmail.php');
   require('classes/UtilSecurity.php');
   require('classes/Programs.php');
   require('classes/Sponsors.php');
   ...

There are many programmers who do not know of the PHP function __autoload (note the two underscores before “autoload”). This function has one parameter that is populated with the classname. If this function is defined then anytime you instantiate a class that hasn’t been defined then the name of the class will be sent to the autoload function. Here is a simple autoload function:

function __autoload($class_name) {
   require '/path/to/includes/' . $class_name . '.php';
}

So if you call:

$my_class = new Auth();

And the class Auth() hasn’t been included yet then PHP would automagically call:

__autoload('Auth');

and the autoload function would include:

require '/path/to/includes/Auth.php';

This is a satisfactory solution, however, it will create one folder that could potential have hundreds of files in it. I will now show you how you can create a well structured and organized library. I personally like to put my files in separate folders. The following is code for an autoload function that will split the classname by capitalized letters and use those as folders.

function __autoload($ClassName) {
   preg_match_all('/[A-Z][^A-Z]*/', $ClassName, $class_array);
   require '/path/to/includes/' . join('/', $class_array[0]) . '.php';
}

So if you call:

$my_class = new KwAuthMain();

And the class KwAuthMain() hasn’t been included yet then PHP would automagically call:

__autoload('KwAuthMain');

and the autoload function would include:

require '/path/to/includes/Kw/Auth/Main.php';

So just make sure you have the folders /Kw/Auth/ in your includes path and then a file named Main.php and then inside the Main.php file you define your class KwAuthMain()

Share and Enjoy:
  • Facebook
  • Twitter
  • Add to favorites
  • email
  • Google Bookmarks

Make a comment