Skip to content

Instantly share code, notes, and snippets.

@texdc
Last active February 16, 2016 16:07
Show Gist options
  • Save texdc/700e46677d2b22a3ebda to your computer and use it in GitHub Desktop.
Save texdc/700e46677d2b22a3ebda to your computer and use it in GitHub Desktop.
build_autoloader()
<?php
namespace texdc\autoload;
use InvalidArgumentException;
/**
* @param array $aDirectoryMap
* @return callable
*/
function build_autoloader(array $aDirectoryMap) : callable
{
validate_directory_map($aDirectoryMap);
return function(string $aClassName) use ($aDirectoryMap)
{
foreach ($aDirectoryMap as $namespace => $sourceDir) {
if (stripos($aClassName, $namespace) !== false) {
include_class_file($aClassName, $namespace, $sourceDir);
break;
}
}
};
}
/**
* @param array $aDirectoryMap
* @throws InvalidArgumentException
*/
function validate_directory_map(array $aDirectoryMap)
{
foreach ($aDirectoryMap as $sourceDir) {
if (!is_dir($sourceDir) || !is_readable($sourceDir)) {
throw new InvalidArgumentException("Invalid source directory [$sourceDir]");
}
}
}
/**
* @param string $aClassName
* @param string $aNamespace
* @param string $aSourceDir
*/
function include_class_file(string $aClassName, string $aNamespace, string $aSourceDir)
{
$fileName = str_replace([$aNamespace, '\\'], [$aSourceDir, DIRECTORY_SEPARATOR], $aClassName) . '.php';
if (is_readable($fileName)) {
include $fileName;
}
}
function include_files(array $aFileList)
{
foreach ($aFileList as $fileName) {
$fileName = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $fileName);
if (is_readable($fileName)) {
include $fileName;
}
}
}
<?php
require 'autoload.php';
use function texdc\autoload\{build_autoloader, include_files};
try {
$ds = DIRECTORY_SEPARATOR;
// could also be: $namespaceDirectoryMap = include 'autoload_namespaces.php';
$namespaceDirectoryMap = [
'foo\\bar\\' => __DIR__ . $ds . 'src' . $ds,
];
spl_autoload_register(build_autoloader($namespaceDirectoryMap));
// could also be: $includeFiles = include 'autoload_files.php';
$includeFiles = [
__DIR__ . $ds . 'src' . $ds . 'my_func.inc',
];
include_files($includeFiles);
} catch (InvalidArgumentException $iae) {
// die($iae->getMessage());
} finally {
unset($namespaceDirectories, $includeFiles, $ds);
}
assert(class_exists('foo\bar\Test'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment