improved autoloader

This commit is contained in:
Timothy Warren 2012-05-22 16:07:30 -04:00
parent 6bcd5ad4d8
commit cade0f5768
10 changed files with 21 additions and 50 deletions

View File

@ -31,67 +31,42 @@ namespace miniMVC;
* *
* @param string * @param string
*/ */
function sys_autoload($name) function _autoload($name)
{ {
$name = str_replace('miniMVC\\', '', $name); if ($name == '') return;
$path = MM_SYS_PATH . "/core/{$name}.php"; // strip off namespaces - they all go to the same folder
$trait_path = MM_SYS_PATH . "/core/traits/{$name}.php"; $name = strtolower($name);
$names = explode('\\', trim($name));
$name = end($names);
if (is_file($path)) // Paths to load from
$sys_path = MM_SYS_PATH . "core/{$name}.php";
$trait_path = MM_SYS_PATH . "core/traits/{$name}.php";
$lib_path = MM_SYS_PATH . "libraries/{$name}.php";
$class_path = MM_APP_PATH . "classes/{$name}.php";
if (is_file($sys_path))
{ {
require_once($path); require_once($sys_path);
} }
elseif (is_file($trait_path)) elseif (is_file($trait_path))
{ {
require_once($trait_path); require_once($trait_path);
} }
} elseif (is_file($lib_path))
// --------------------------------------------------------------------------
/**
* Function to autoload libraries/classes
*
* @param string
*/
function autoload($name)
{
// strip off namespaces - they all go to the same folder
$names = explode('\\', $name);
$name = end($names);
// In a subdirectory? No problem
if (strpos("/", $name) !== FALSE)
{ {
$n = explode("/", $name); require_once($lib_path);
$name = $n[count($n) -1];
} }
// Try system library first, then app library if (is_file($class_path))
$name = strtolower($name);
$path = MM_SYS_PATH . "libraries/{$name}.php";
if ( ! is_file($path))
{ {
$path = MM_APP_PATH . "classes/{$name}.php"; require_once($class_path);
}
// Load the class file if need be
if ( ! class_exists($name))
{
if (is_file($path))
{
require_once($path);
}
} }
} }
// Load system libraries/traits // Start the autoloader
spl_autoload_register('miniMVC\sys_autoload'); spl_autoload_register('miniMVC\_autoload');
// Start the library autoloader
spl_autoload_register('miniMVC\autoload');
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// ! Error handling / messages // ! Error handling / messages
@ -465,13 +440,9 @@ function route()
$class = new $controller(); $class = new $controller();
return call_user_func_array([&$class, $func], []); return call_user_func_array([&$class, $func], []);
} }
// Function doesn't exist...404
show_404();
die();
} }
// If it gets here, it's still a 404 // Function doesn't exist...404
show_404(); show_404();
} }