Skip to content

Instantly share code, notes, and snippets.

@md-riaz
Created September 3, 2024 05:49
Show Gist options
  • Save md-riaz/af7a73db62baa3dfe3ba2d85cb26663b to your computer and use it in GitHub Desktop.
Save md-riaz/af7a73db62baa3dfe3ba2d85cb26663b to your computer and use it in GitHub Desktop.
<?php
private static function autoload()
{
spl_autoload_register(function ($class) {
// Define base directories for known namespaces
$baseDirs = [
'Framework\\Core\\' => FRAMEWORK_PATH . 'Core/',
'App\\' => APP_PATH
];
// Handle dynamic autoloading for Libraries
$librariesDir = FRAMEWORK_PATH . 'Libraries/';
$namespaceParts = explode('\\', $class);
if (count($namespaceParts) > 1) {
// Check if the first part of the namespace matches a known library
$firstNamespace = array_shift($namespaceParts);
$libraryDir = $librariesDir . $firstNamespace . '/src/';
// If the directory exists, add it to the base directories
if (is_dir($libraryDir)) {
$baseDirs[$firstNamespace . '\\'] = $libraryDir;
}
}
// Loop through each namespace prefix
foreach ($baseDirs as $prefix => $baseDir) {
// Check if the class uses the namespace prefix
$prefixLength = strlen($prefix);
if (strncmp($prefix, $class, $prefixLength) === 0) {
// Get the relative class name
$relativeClass = substr($class, $prefixLength);
// Replace namespace separators with directory separators
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
// If the file exists, require it
if (file_exists($file)) {
require $file;
return;
}
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment