Created
August 26, 2018 21:06
-
-
Save mladoux/2ac5a1c74fea2eb720d848c2c92e8d59 to your computer and use it in GitHub Desktop.
SystemLoader - A very simplle PHP class autoloader. Does not work with underscored class path conventions, but could easilly be modified to do so.
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 | |
/** | |
* SystemLoader | |
* | |
* Autoloader for project libs and dependencies. | |
* | |
* @author Mark LaDoux <[email protected]> | |
*/ | |
class SystemLoader | |
{ | |
/** | |
* array of file paths to search for libraries. | |
* | |
* @access protected | |
* @var array | |
*/ | |
protected $paths = []; | |
/** | |
* addRoute | |
* | |
* @access public | |
* @param string $path base filepath to search for libraries | |
* @return void | |
*/ | |
public function addRoute(string $path) | |
{ | |
// ensure consistency in file path separator conventions. | |
str_replace('\\', '/', $path); | |
// ensure a trailing '/'. | |
if (substr($path, -1) != '/') { | |
$path = $path . '/'; | |
} | |
// Add path to searchable array. | |
$this->paths[] = $path; | |
} | |
/** | |
* Autoload a class. | |
* | |
* @access public | |
* @param string $class_name Name of class to load | |
* @return void | |
*/ | |
public function autoload(string $class_name) | |
{ | |
// Iterate through all the searchable paths | |
foreach ($this->paths as $path) { | |
// create file_path based on the class name, don't forget to flip | |
// the slashes in the namespace! | |
$file_path = str_replace('\\', '/', $path . $class_name . '.php'); | |
// check if the class name is loaded, if not, and the file is readable, | |
// load it! | |
if (! class_exists($class_name, FALSE) && is_readable($file_path)) { | |
include_once $file_path; | |
// break out of the loop, we're done searching now! | |
break; | |
} | |
} | |
} | |
/** | |
* Register the autoloader | |
* | |
* @access public | |
* @return void | |
*/ | |
public function register() | |
{ | |
spl_autoload_register([$this, 'autoload']); | |
} | |
} | |
$sysload = new SystemLoader; | |
$sysload->addRoute('/absolute/path/to/root/of/libraries/'); | |
$sysload->register(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment