Created
January 29, 2021 13:00
-
-
Save sharafc/296af7cf0e36f4dbfe0c287a4c999e69 to your computer and use it in GitHub Desktop.
Very simple Autoloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Autoloader which loads Classes, Interfaces and Traits | |
* Expects that Traits are named xy.trait.php and | |
* Classes/Interfaces are named xy.class.php | |
* | |
* Needs the following defined constants to work: | |
* TRAITS_PATH -> Path to the directory containing traits | |
* TRAIT_NAMES -> Whitelist for traits | |
* CLASSES_PATH -> Path to the directory containing Classes and Interfaces | |
* | |
* SPL takes care of resolving the filename | |
* @see https://www.php.net/manual/en/function.spl-autoload-register.php | |
* | |
* @param string $name The name of the file to be loaded | |
* @return void | |
*/ | |
function autoLoader($name) { | |
if (in_array($name, TRAIT_NAMES)){ | |
$path = TRAITS_PATH . $name . '.trait.php'; | |
} else { | |
$path = CLASSES_PATH . $name . '.class.php'; | |
} | |
if(file_exists($path)) { | |
require_once($path); | |
} else { | |
error_log('File in path ' . $path . ' not found'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define('CLASSES_PATH', 'Class' . DIRECTORY_SEPARATOR); | |
define('TRAITS_PATH', 'Trait' . DIRECTORY_SEPARATOR); | |
define('TRAIT_NAMES', []); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once('include/autoLoader.inc.php'); | |
// Autoloader | |
spl_autoload_register('autoLoader'); | |
?> | |
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Auto Loader</title> | |
</head> | |
<body> | |
<p>Do your things!</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment