好吧,我遇到了类似的问题,并决定寻找可重用和可扩展的东西。所以,我只是为了演示科林的答案而为你修剪了它。代码可以改进:)
<?php
/**
* Autoloader
* @Usage:
* // set autoload paths
* Loader::setPaths(
* array("interface_path"=>dirname(__FILE__). "/core"),
* array("plugin_path"=>"/var/www/awesome-app/plugins"),
* array("controller_path"=>dirname(__FILE__). "/controllers")
* );
*
*
* // Now, the magic
* Loader::registerAutoloads();
*/
class Loader{
protected static $interfacePath = '';
protected static $pluginPath = '';
protected static $controllerPath = '';
/**
* Set paths to autoload classes
*
* @param string $application
* @param string $library
* @todo this part can be cleaner/smarter with less code.
* Replace "" for with constants as default folders to search
*/
public static function setPaths($autoload_paths= null)
{
if(is_array($autoload_paths)){
self::$interfacePath = array_key_exists("interface_path", $autload_paths) ?
$autoload_paths["interface_path"] : "";
self::$interfacePath = array_key_exists("plugin_path", $autload_paths) ?
$autoload_paths["plugin_path"] : "";
self::$interfacePath = array_key_exists("controller_path", $autload_paths) ?
$autoload_paths["controller_path"] : "";
}
}
/**
* Registers autoload functions
*
*/
public static function registerAutoloads() {
spl_autoload_register('Loader::loadInterface');
spl_autoload_register('Loader::loadPlugin');
spl_autoload_register('Loader::loadController');
if ( function_exists('__autoload') ) {
spl_autoload_register('__autoload');
}
}
/**
* Checks if a given file exists and load it
*
* @param string $filename
* @return bool
*/
protected static function check($filename)
{
if(file_exists($filename)){
include_once $filename;
return true;
}
return false;
}
/**
* Interface Loader
*
* @param string $className
* @return bool
*/
static function loadInterface($className)
{
return self::check(
sprintf('%s/%s_interface.php',self::$interfacePath, low($className))
);
}
/**
* Plugin Loader
*
* @param string $className
* @return bool
*/
static function loadPlugin($className)
{
return self::check(
sprintf('%s/%s_plugin.php',self::$pluginPath,low($className))
);
}
/**
* Controller Loader.
*
* @param string $className
* @return bool
*/
static function loadController($className){
$fileName = camelCaseToUnderscore($className);
return self::check(
sprintf('%s/%s_controller.php',self::$controllerPath,$fileName)
);
}
}
?>
It uses PHP's autoload functions, so please make sure you have them.
To resolve conflicts, i added a small registry class(sort of key/value store for unique variables and functions) that fixed conflicts.
It Also improved performance.
Might be an overkill for your kind of work, but it helped me since mine was quite a big project.