Skip to content

Instantly share code, notes, and snippets.

@mladoux
Created August 26, 2018 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mladoux/2ac5a1c74fea2eb720d848c2c92e8d59 to your computer and use it in GitHub Desktop.
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.
<?php
/**
* SystemLoader
*
* Autoloader for project libs and dependencies.
*
* @author Mark LaDoux <mark.ladoux@gmail.com>
*/
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