<?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();