Created
June 9, 2014 04:17
-
-
Save dukeofgaming/4cdee61ea2ec2734c4b5 to your computer and use it in GitHub Desktop.
Register autoload of classes in a folder with customizable file naming rule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author dukeofgaming | |
* @param string $path The path where the files with the classes are located (1 class per file always) | |
* @param function $rule Callback that receives the file name as parameter and returns the class name | |
*/ | |
function autoloadPath($path,$rule=null){ | |
$absolute_path = dirname(__FILE__).DS.$path; | |
$files = array_filter( | |
scandir($absolute_path), | |
create_function('$filename','return preg_match(\'/\.php$/\', $filename);') | |
); | |
$classes = array(); | |
if($rule === null){ | |
function class_name($filename){ | |
if(preg_match('/(.*)\.php$/', $filename, $matches)){ | |
return $matches[1]; | |
} | |
} | |
foreach($files as $file){ | |
$classes[class_name($file)] = $absolute_path.DS.$file; | |
} | |
}else{ | |
foreach($files as $file){ | |
$classes[$rule($file)] = $absolute_path.DS.$file; | |
} | |
} | |
spl_autoload_register( | |
create_function('$class',' | |
$classes = '.var_export($classes,true).'; | |
if(array_key_exists($class, $classes)){ | |
require_once($classes[$class]); | |
} | |
') | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment