Tag: code

A better autoloader

I’ve seen a few folks refer to an old autoload piece of code written a long time ago in a galaxy far far away. Anyway this is a newer more updated autoloader function you can add to the bottom of your config.php file.

Note the array you can use to define multiple auto-load locations so you don’t have to keep everything in core.

Stick this code at the bottom of your config.php file. Or, make a file called myautoloader.php and include it in your config.php file for a cleaner setup.

 

/**
* Autoloader function
*
* @param $class_name
* @return void
*/
function __autoloader($class_name)
{

//class directories
$directories = array(
APPPATH . ‘core/’,
//add more autoloading folders here… and you’re done.
);

//for each directory
foreach($directories as $directory)
{
//see if the file exsists
if(file_exists($directory.$class_name . ‘.php’))
{
require_once($directory.$class_name . ‘.php’);
//only require the class once, so quit after to save effort (if you got more, then name                    //them something else
return;
}
}

}

spl_autoload_register(‘__autoloader’);