PHP classes autoload (namespaces)

I like PHP, OOP is very easy with it and Zend Framework is a charm once you start to get use to it.

One of the coolest things in the latest release of PHP are namespaces, really they are cool! Weird as it may sound coding in PHP reminds me of Java ;P Namespaces allows me to give some order to my code and avoids overwriting other code, it’s pretty neat but one thing I’ve been meesing around is autoloading namespaced classes.

After a few hours I’ve managed to code a simple classes and namespaces autoloader, it’s the first version so I’ll be enhancing it over the next days.

I’ll try to make it as clear as possible. Code will be commented. Hope it helps someone 😀

Ok there are two kinds of files I want to autoload: namespaced classes and normal classes.

For both of them I’ll need a path:

define('CLSS_PTH','path_to_classes_folder');
define('NMSPCS_PTH','path_to_namespaces_folder');

Now to the function!

For standarization purposes class names can be camelcase but when searching the file’s name it must be lowercase.

I’ll code the body of the autoload function provided by php.

function __autoload($class){
  $class = strtolower($class);
  if(strpos('\\',$class)){
    $class = preg_replace('/\\/',DIRECTORY_SEPARATOR,$class);
    require_once (NMSPCS_PTH . DIRECTORY_SEPARATOR . $class . ".php");
  }
  else{
    require_once (CLSS_PTH . DIRECTORY_SEPARATOR . $class . ".php");
  }
}

That’s it… now I just read about a php function called set_include_path and just saw other way to autoload classes… I’ll leave that for version 2 hehehe

Tags:

Comments are closed.