Navigation

PHP Autoloader

I'm still working diligently on WiredCMS in my spare time, and ran across a grate trick for OOP with PHP. Traditionally in PHP, wach class has its own file, eg. class.inc.php.

When you have a script that requires several classes, this gets tedious to include every class file. There is a built-in autoloader method for classes, called __autoload(). The problem with this, from what I have read, is that you can run into issues when using this method, and using 3rd party web apps, as the methods can clash. To get around this, I wrote my own autoloader method.

Please note, I am using the MVC model for OOP, and so I have both model classes (.inc.php) and controller classes (.controller.php), so this method may not be exactly what you need, but can be modified easily enough.

  1. public static function autoload($c){
  2.  if(file_exists("./includes/".strtolower($c).".inc.php") && require_once("./includes/".strtolower($c).".inc.php")) {
  3.         return true;
  4.  } elseif (file_exists("./includes/".strtolower(str_ireplace('controller','',$c)).".controller.php") && require_once("./includes/".strtolower(str_ireplace('controller','',$c)).".controller.php")) {
  5.  return true;
  6.  }else {
  7.      trigger_error("Could not load class '{$c}'", E_USER_WARNING);
  8.      return false;
  9.  }
  10. }

To initialize this method as an actual autoloading class, you must callit the following way:

  1. spl_autoload_register(array("Core","autoload"));

Above: the array passed to spl_autoload_register specifies the class the method belongs to, followed by the method name.

The argument passed to the autoload method is simply the class name. If I was to call :

  1. Core::SomeFunction();

The class 'Core' would be passed to the autoload method as $c.

And that is all there is to it! I hope this helps out some developers, as this method has helped me and saved me a lot of time!

Autoloader implementation

PHP autoloader can find any class in a class path in any file. The file name must not follow any convention. It also works perfectly with any other autoloader.

YcxMRpUgXi