Please review my Autoloader, which is the first file included in index.php
Note that there is no resource with the same name for trait, interface and class. Each resource has it's own name. And even if some class is named "Ha" and some trait is named "Ha", one of them has specific namespace for this.
<?php
### Autoload class ###
class Autoload
{
# The path for classes, traits or interfaces #
private static $path = 'private/Model/';
# The resource files by default will be NULL #
private static $resource_files = null;
# Search for resource_files in recursive mode #
private static function recursive_glob($pattern)
{
$resource_files = glob($pattern);
foreach(glob(dirname($pattern).'/*', GLOB_ONLYDIR | GLOB_NOSORT) as $directory)
{
$resource_files = array_merge(
$resource_files,
self::recursive_glob($directory.'/'.basename($pattern))
);
}
return $resource_files;
}
# Order array to start with files that has the name like the $resource or closely... #
private static function order_resource_files($resource)
{
$resource_name = explode('\\', $resource);
$resource_name = end($resource_name);
foreach(self::$resource_files as $file_key => $file)
{
if(stripos($file, $resource_name) !== false)
{
self::$resource_files[-1] = $file;
unset(self::$resource_files[$file_key]);
ksort(self::$resource_files);
self::$resource_files = array_values(self::$resource_files);
}
}
}
# Find resource #
public static function find($resource)
{
# Set $resource_files if is NULL #
if(!self::$resource_files)
{
self::$resource_files = self::recursive_glob(self::$path.'*.php');
}
# Order $resource_files by given resource #
self::order_resource_files($resource);
# Now that we have the $resource_files array, we can start searching #
foreach(self::$resource_files as $file_key => $file)
{
# First, remove the file from array #
unset(self::$resource_files[$file_key]);
# Include file #
require_once $file;
# If resource exists now, then we can stop and search for other resources later #
if(class_exists($resource) || trait_exists($resource) || interface_exists($resource))
{
break;
}
}
}
}
### Check PHP version and call Autoload::find ###
if(version_compare(PHP_VERSION, '5.1.2', '>='))
{
if(version_compare(PHP_VERSION, '5.3.0', '>='))
{
spl_autoload_register('Autoload::find', true, true);
}
else
{
spl_autoload_register('Autoload::find');
}
}
else
{
function __autoload($resource)
{
Autoload::find($resource);
}
}