Skip to content

Instantly share code, notes, and snippets.

@ivanscm
Created February 23, 2012 03:39
Show Gist options
  • Select an option

  • Save ivanscm/1889876 to your computer and use it in GitHub Desktop.

Select an option

Save ivanscm/1889876 to your computer and use it in GitHub Desktop.
autoloader
<?php
class Autoload
{
private $classes_file = '';
private $classes = array();
function __construct($autoload = 'cache/autoload')
{
$this->classes_file = ROOT_DIR . '/' . $autoload;
}
function existsClasses()
{
return file_exists($this->classes_file);
}
function readAutoload()
{
return unserialize(file_get_contents($this->classes_file));
}
function writeAutoload($classes = array())
{
return file_put_contents($this->classes_file, serialize($classes));
}
function getClassName($file)
{
$php_file = file_get_contents($file);
preg_match_all('#.*(class|interface)\s(\w+)#', $php_file, $classes_list);
if (count($classes_list) > 2 && isset($classes_list[2][0]))
{
return $classes_list[2];
}
else
return FALSE;
}
function scanClass($dir)
{
$dir_list = new DirectoryIterator($dir);
foreach ($dir_list as $file)
{
if ($file->isDir() && !$file->isDot())
$this->scanClass($file->getPathname());
if ($file->isFile() && strtolower(pathinfo($file->getFilename(), PATHINFO_EXTENSION)) == 'php')
{
$classes_list = $this->getClassName($file->getPathname());
if ($classes_list !== FALSE)
foreach ($classes_list as $class_name)
$this->classes[strtoupper($class_name)] = $file->getPathname();
}
}
}
function registerAutoload()
{
spl_autoload_register ('self::autoload');
if (!$this->existsClasses())
{
$this->scanClass(ROOT_DIR);
$this->writeAutoload($this->classes);
}
else
$this->classes = $this->readAutoload();
}
function autoload($class_name)
{
$class_name = strtoupper($class_name);
if (isset($this->classes[$class_name]))
include $this->classes[$class_name];
}
}
?>
define('ROOT_DIR', $_SERVER['DOCUMENT_ROOT']);
define('DEBUG', TRUE);
include 'engine/autoload.php';
$autoloader = new Autoload();
$autoloader->registerAutoload();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment