Skip to content

Instantly share code, notes, and snippets.

@dukeofgaming
Created June 9, 2014 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dukeofgaming/4cdee61ea2ec2734c4b5 to your computer and use it in GitHub Desktop.
Save dukeofgaming/4cdee61ea2ec2734c4b5 to your computer and use it in GitHub Desktop.
Register autoload of classes in a folder with customizable file naming rule
<?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