ircbot/SocketFramework/Classes/Core/ClassLoader.php
Jan Philipp Timme e702124895 [TASK] Finalized modifications on ClientManager.
[TASK] Added support for further class paths to ClassLoader.
[TASK] Started to implement the irc client dispatcher. (partially works now)
2011-12-03 20:58:08 +01:00

75 lines
2.0 KiB
PHP

<?php
namespace JPT\SocketFramework\Core;
/**
* Simple class to capsule the classloader so more than one autoload function can be used.
*
* @author JPT
*/
class ClassLoader {
/**
* 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;
}
/**
* Autoloader function.
*
* @throws \Exception
* @param string $className
* @return void
*/
public function loadClass($className) {
$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;
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);
}
}
?>