Skip to content

Instantly share code, notes, and snippets.

@tafhimulkabir
Last active September 20, 2023 19:01
Show Gist options
  • Save tafhimulkabir/ffe0e73dda06b4c7238b38a899a68de1 to your computer and use it in GitHub Desktop.
Save tafhimulkabir/ffe0e73dda06b4c7238b38a899a68de1 to your computer and use it in GitHub Desktop.
A Simple PHP Class for Autoloading
<?php
/**
* AutoLoader.php
*/
declare(strict_types=1);
namespace Autoloader;
/**
* Autoloader class for automatically loading PHP classes based on namespaces.
*/
class AutoLoader
{
/**
* File extension for PHP class files.
*/
private const EXT = '.php';
/**
* Load a class file based on its namespace.
*
* @param string $className The fully qualified class name (with namespace).
* @return void
*/
private static function loadClass(string $className): void
{
// Split the class name into namespace segments.
$namespaceSegments = explode('\\', $className);
// Get the class file name.
$fileName = end($namespaceSegments);
// Remove the class name from the segments array.
array_pop($namespaceSegments);
// Construct the relative file path.
$relativePath = implode(DIRECTORY_SEPARATOR, array_map('trim', $namespaceSegments));
// Get the absolute path to the class file.
$absolutePath = realpath($relativePath);
// Construct the full path to the class file.
$fullPath = $absolutePath . DIRECTORY_SEPARATOR . $fileName . self::EXT;
try {
// Check if the class file exists and require it.
if (file_exists($fullPath)) {
require_once $fullPath;
} else {
// Handle the case where the class file does not exist.
throw new \RuntimeException("Class file not found: $className");
}
} catch (\RuntimeException $e) {
// Handle the exception (e.g., log the error or display an error message).
// You can customize the error handling here.
echo 'Autoloader Error: ' . $e->getMessage();
// Optionally, you can also re-throw the exception to propagate it further.
// throw $e;
}
}
/**
* Register the autoloader with spl_autoload_register().
*
* @return void
*/
public static function register(): void
{
spl_autoload_register([self::class, 'loadClass']);
}
/**
* Unregister the autoloader with spl_autoload_unregister().
*
* @return void
*/
public static function unregister(): void
{
spl_autoload_unregister([self::class, 'loadClass']);
}
}
// Register the autoloader when AutoLoader.php is included.
AutoLoader::register();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment