2011-12-03 12:28:02 +01:00
|
|
|
<?php
|
|
|
|
namespace JPT\SocketFramework\Core;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Simple class to capsule the classloader so more than one autoload function can be used.
|
|
|
|
*
|
|
|
|
* @author JPT
|
|
|
|
*/
|
|
|
|
class ClassLoader {
|
|
|
|
|
2011-12-03 20:58:08 +01:00
|
|
|
/**
|
|
|
|
* Contains class name prefix and path prefix for all class paths it shall handle
|
|
|
|
*
|
|
|
|
* @var array
|
|
|
|
*/
|
|
|
|
protected $classNameMapping = array();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Default constructor.
|
|
|
|
* Registers the main class path for the socket framework.
|
|
|
|
*/
|
|
|
|
public function __construct() {
|
|
|
|
$this->classNameMapping = array(
|
|
|
|
'JPT\SocketFramework' => 'SocketFramework' . \DIRECTORY_SEPARATOR . 'Classes'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Registers a new class path for the autoloader
|
|
|
|
*
|
|
|
|
* @param string $classNamePrefix
|
|
|
|
* @param string $pathPrefix
|
|
|
|
*/
|
|
|
|
public function addClassPathMapping($classNamePrefix, $pathPrefix) {
|
|
|
|
$this->classNameMapping[$classNamePrefix] = $pathPrefix;
|
|
|
|
}
|
|
|
|
|
2011-12-03 12:28:02 +01:00
|
|
|
/**
|
|
|
|
* Autoloader function.
|
|
|
|
*
|
|
|
|
* @throws \Exception
|
|
|
|
* @param string $className
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function loadClass($className) {
|
2011-12-03 20:58:08 +01:00
|
|
|
$matchingClassNamePrefix = FALSE;
|
|
|
|
foreach($this->classNameMapping AS $classNamePrefix => $pathPrefix) {
|
|
|
|
if(substr($className, 0, strlen($classNamePrefix)) !== $classNamePrefix) continue;
|
|
|
|
$matchingClassNamePrefix = TRUE;
|
|
|
|
$classNameSuffix = substr($className, strlen($classNamePrefix), strlen($className));
|
|
|
|
$fileName = $this->classNameMapping[$classNamePrefix];
|
|
|
|
$fileName .= \DIRECTORY_SEPARATOR . str_replace('\\', \DIRECTORY_SEPARATOR, $classNameSuffix) . ".php";
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if($matchingClassNamePrefix === FALSE) return;
|
2011-12-03 12:28:02 +01:00
|
|
|
if(file_exists($fileName) === TRUE) {
|
|
|
|
require_once($fileName);
|
|
|
|
} else {
|
|
|
|
throw new \Exception("Could not load class: '" . $className . "' - File does not exist: '" . $fileName . "'!", 1289659295);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Simple function that registers loadClass as an autoloader.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
* @throws Exception in case spl_autoload_register fails.
|
|
|
|
*/
|
|
|
|
public function initialize() {
|
|
|
|
spl_autoload_register(array($this, 'loadClass'), TRUE, TRUE);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
?>
|