Saturday, January 8, 2011

PHP Autoload

I fought it for a long time, but I think I am finally convinced that PHP autoload functionality is a good idea.

In case anyone out there needs an example, the following is a custom autoload function that allows for multiple directories to be checked for class files.

Just a quick note, the 'THEFULLPATH' constant should already be set to your server path, and the directories array should be updated to include the directories that your class files are in.

// global function for autoload functionality
function class_autoload($class_name)
{
   // directories where class files are located
   $directory_list = array(
      THEFULLPATH.'common/',
      THEFULLPATH.'models/',
   );

   // for consistency make sure the class name is lower case
   $class_name = strtolower($class_name);

   // for each directory in our directory list
   foreach ($directory_list as $directory)
   {
      // does the file exist? notice the naming convention used here
      // is classname.class.php, feel free to use your own naming 
      // structure and modify the following lines to fit, just 
      // be consistent
      if (file_exists($directory.$class_name.'.class.php'))
      {
         require($directory.$class_name . '.class.php');
         // only require the class once, we exit here to cut down on 
         // processing time
         return;
      } 
   }

   // if we are dealing with another class that had a different 
   // naming convention we add it here if you have many classes 
   // like this (and they should be common libraries, since if 
   // you are writing them they should follow your convention) 
   // you may want to change this to a switch statement
   if ($class_name == 'phpmailer') {
      require(THEFULLPATH."common/PHPMailer/class.phpmailer.php");
   }
}

Once you have created your function, you will need to register it with PHP

spl_autoload_register('class_autoload');

Congratulations, you now have a working autoload function!

For more information on PHP autoload, read the manual Here

No comments:

Post a Comment