X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;ds=sidebyside;f=inc%2Floader%2Fclass_ClassLoader.php;h=134b8c10d4af9d7a533065d105da41c4f92c09c6;hb=886d3459eb15f9bc6b15051b2fe2d3605c19a5d4;hp=faee2d4dfb9d5ab7b905e4461513d397c71696b8;hpb=666210d9addd5d19b9dba98b05e8b824b4116c9a;p=mailer.git diff --git a/inc/loader/class_ClassLoader.php b/inc/loader/class_ClassLoader.php index faee2d4dfb..134b8c10d4 100644 --- a/inc/loader/class_ClassLoader.php +++ b/inc/loader/class_ClassLoader.php @@ -2,10 +2,28 @@ /** * This class loads class include files with a specific prefix and suffix * - * @author Roland Haeder - * @version 1.1 + * @author Roland Haeder + * @version 0.0.0 + * @copyright Copyright (c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . * * ---------------------------------- + * 1.2 + * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class * 1.1 * - loadClasses rewritten to fix some notices * 1.0 @@ -13,15 +31,25 @@ * ---------------------------------- */ class ClassLoader { + /** + * Instance of this class + */ + private static $selfInstance = null; + /** * Configuration array */ private $cfg = array(); /** - * An ArrayObject for found classes + * Array with all classes */ - private $classes = null; + private $classes = array(); + + /** + * List of loaded classes + */ + private $loadedClasses = array(); /** * Suffix with extension for all class files @@ -36,12 +64,12 @@ class ClassLoader { /** * Length of the suffix. Will be overwritten later. */ - private $sufLen = 0; + private $suffixLen = 0; /** * Length of the prefix. Will be overwritten later. */ - private $preLen = 0; + private $prefixLen = 0; /** * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner @@ -50,29 +78,34 @@ class ClassLoader { private $ignoreList = array(); /** - * An ArrayList object for include directories + * Debug this class loader? (true = yes, false = no) */ - private $dirList = null; + private $debug = false; /** - * Debug this class loader? (true = yes, false = no) + * Wether the file list is cached or not */ - private $debug = false; + private $listCached = false; /** - * Counter for scanned directories (debug output) + * Wethe class content has been cached */ - private $dirCnt = 0; + private $classesCached = false; /** - * Counter for loaded classes (debug output) + * Filename for the list cache */ - private $classCnt = 0; + private $listCacheFQFN = ""; /** - * Instance of this class + * Cache for class content */ - private static $thisInstance = null; + private $classCacheFQFN = ""; + + /** + * Counter for loaded include files + */ + private $total = 0; /** * The *public* constructor @@ -81,44 +114,111 @@ class ClassLoader { * @return void */ public function __construct (FrameworkConfiguration $cfgInstance) { - // Init the array list - $this->dirList = new ArrayObject(); + // Set configuration instance + $this->cfgInstance = $cfgInstance; + + // Construct the FQFN for the cache + if (!defined('DEVELOPER')) { + $this->listCacheFQFN = $this->cfgInstance->readConfig('local_db_path') . "list-" . $this->cfgInstance->readConfig('app_name') . ".cache"; + $this->classCacheFQFN = $this->cfgInstance->readConfig('local_db_path') . "class-" . $this->cfgInstance->readConfig('app_name') . ".cache"; + } // END - if // Set suffix and prefix from configuration - $this->suffix = $cfgInstance->readConfig("class_suffix"); - $this->prefix = $cfgInstance->readConfig("class_prefix"); + $this->suffix = $cfgInstance->readConfig('class_suffix'); + $this->prefix = $cfgInstance->readConfig('class_prefix'); // Estimate length of prefix and suffix for substr() function (cache) - $this->sufLen = strlen($this->suffix); - $this->preLen = strlen($this->prefix); + $this->suffixLen = strlen($this->suffix); + $this->prefixLen = strlen($this->prefix); - // Set configuration instance - $this->cfgInstance = $cfgInstance; + // Set own instance + self::$selfInstance = $this; - // Initialize the classes list - $this->classes = new ArrayObject(); + // Skip here if no dev-mode + if (defined('DEVELOPER')) return; - // Set own instance - self::$thisInstance = $this; + // IS the cache there? + if (file_exists($this->listCacheFQFN)) { + // Get content + $cacheContent = file_get_contents($this->listCacheFQFN); + + // And convert it + $this->classes = unserialize($cacheContent); + + // List has been restored from cache! + $this->listCached = true; + } // END - if + + // Does the class cache exist? + if (file_exists($this->classCacheFQFN)) { + // Then include it + require($this->classCacheFQFN); + + // Mark the class cache as loaded + $this->classesCached = true; + } // END - if + } + + /** + * The destructor makes it sure all caches got flushed + * + * @return void + */ + public function __destruct () { + // Skip here if dev-mode + if (defined('DEVELOPER')) return; + + // Skip here if already cached + if ($this->listCached === false) { + // Writes the cache file of our list away + $cacheContent = serialize($this->classes); + file_put_contents($this->listCacheFQFN, $cacheContent); + } // END - if + + // Skip here if already cached + if ($this->classesCached === false) { + // Generate a full-cache of all classes + $cacheContent = ""; + foreach ($this->loadedClasses as $fqfn) { + // Load the file + $cacheContent .= file_get_contents($fqfn); + } // END - foreach + + // And write it away + file_put_contents($this->classCacheFQFN, $cacheContent); + } // END - if } /** * Getter for an instance of this class * - * @return $thisInstance An instance of this class + * @return $selfInstance An instance of this class */ public final static function getInstance () { - return self::$thisInstance; + // Is the instance there? + if (is_null(self::$selfInstance)) { + // Get a new one + self::$selfInstance = new ClassLoader(FrameworkConfiguration::getInstance()); + } // END - if + + // Return the instance + return self::$selfInstance; } /** * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix * - * @param $basePath The relative base path to PATH constant for all classes - * @param $ignoreList An optional list (array or string) of directory names which shall be ignored + * @param $basePath The relative base path to 'base_path' constant for all classes + * @param $ignoreList An optional list (array or string) of directory names which shall be ignored * @return void */ public function loadClasses ($basePath, $ignoreList = array() ) { + // Is a list has been restored from cache, don't read it again + if ($this->listCached === true) { + // Abort here + return; + } + // Convert string to array if (!is_array($ignoreList)) $ignoreList = array($ignoreList); @@ -128,6 +228,7 @@ class ClassLoader { $ignoreList[] = "."; $ignoreList[] = ".."; $ignoreList[] = ".htaccess"; + $ignoreList[] = ".svn"; // Keep it in class for later usage $this->ignoreList = $ignoreList; @@ -139,122 +240,137 @@ class ClassLoader { // If the basePath is false it is invalid if ($basePath2 === false) { - // TODO: Do not die here. + /* @todo: Do not die here. */ die("Cannot read {$basePath} !"); } else { // Set base path $basePath = $basePath2; } - // Load all super classes (backward, why ever this name... :-? ) - // We don't support sub directories here... - $this->scanLocalPath($basePath); - - // While there are directories in our list scan them for classes - $cnt = 0; - while ($cnt != $this->dirList->count()) { - for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) { - // Get current path - $currPath = $idx->current(); - - // Remove the current entry or else this will lead into a infinite loop - $this->dirList->offsetSet($idx->key(), ""); - - // Scan the directory - $this->scanLocalPath($currPath); - } - - // Check if we can leave - $cnt = 0; - for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) { - if ($idx->current() == "") $cnt++; - } - } + // Get a new iterator + //* DEBUG: */ echo "Base path: {$basePath}
\n"; + $iterator = new RecursiveDirectoryIterator($basePath); + $recursive = new RecursiveIteratorIterator($iterator); + foreach ($recursive as $entry) { + // Get filename from iterator + $fileName = $entry->getFileName(); + + // Is this file wanted? + //* DEBUG: */ echo "FOUND:{$fileName}
\n"; + if ((!in_array($fileName, $this->ignoreList)) && (substr($fileName, 0, $this->prefixLen) == $this->prefix) && (substr($fileName, -$this->suffixLen, $this->suffixLen) == $this->suffix)) { + // Get the FQFN and add it to our class list + $fqfn = $entry->getRealPath(); + //* DEBUG: */ echo "ADD: {$fileName}
\n"; + $this->classes[$fileName] = $fqfn; + } // END - if + } // END - foreach } /** - * The local path scanner. A found class will be loaded immediately - * @param $localPath The local path which shall be recursively scanned for include files - * @return void - */ - private function scanLocalPath ($localPath) { - // Empty path names will be silently ignored - if (empty($localPath)) return; - - // TODO: No dies here, mayybe this should be rewritten to throw an exception? - $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($localPath); - while ($dirClass = $dirInstance->readDirectoryExcept($this->ignoreList)) { - // We need the relative dir name as an array index some lines below - $dirClass2 = $dirClass; - - // A nice replacement for a simple dot ;) - $dirClass = sprintf("%s/%s", $localPath, $dirClass); - - // Is a readable file with configured prefix and suffix? All other - // files will silently be ignored! - //* DEBUG: */ print "Prefix=".$this->prefix."(".substr($dirClass2, 0 , $this->preLen).")\n"; - //* DEBUG: */ print "Suffix=".$this->suffix."(".substr($dirClass2, -$this->sufLen, $this->sufLen).")\n"; - //* DEBUG: */ print "ENTRY={$dirClass}\n"; - if ( - (is_file($dirClass)) - && (is_readable($dirClass)) - && (substr($dirClass2, 0 , $this->preLen) == $this->prefix) - && (substr($dirClass2, -$this->sufLen, $this->sufLen) == $this->suffix) - ) { - // Class found so load it instantly - //* DEBUG: */ print "CLASS={$dirClass}\n"; - $this->classes->append($dirClass); - $this->classCnt++; - } elseif (is_dir($dirClass) && !in_array($dirClass2, $this->ignoreList)) { - // Directory found and added to list - //* DEBUG: */ print "DIR={$dirClass}\n"; - if ($dirClass2 == "interfaces") { - $this->scanLocalPath($dirClass); - } else { - $this->dirList->append($dirClass); - } - $this->dirCnt++; - } - //* DEBUG: */ print "LOOP!\n"; - } // END - while - - // Close directory handler - $dirInstance->closeDirectory(); - - // Output counter in debug mode - if (defined('DEBUG_MODE')) print(sprintf("[%s:] %d Klassendateien in %d Verzeichnissen gefunden und geladen.
\n", - __CLASS__, - $this->classCnt, - $this->dirCnt - )); + * Load extra config files + * + * @return void + */ + public function loadExtraConfigs () { + // Backup old prefix + $oldPrefix = $this->prefix; + + // Set new prefix (temporary!) + $this->prefix = "config-"; + $this->prefixLen = strlen($this->prefix); + + // Set base directory + $basePath = sprintf("%sinc/config/", $this->cfgInstance->readConfig('base_path')); + + // Load all classes from the config directory + $this->loadClasses($basePath); + + // Include these extra configs now + $this->includeExtraConfigs(); + + // Set the prefix back + $this->prefix = $oldPrefix; + $this->prefixLen = strlen($this->prefix); + } /** - * Includes all found classes + * Tries to find the given class in our list. This method ignores silently + * missing classes or interfaces. So if you use class_exists() this method + * does not interrupt your program. + * + * @param $className The class we shall load * @return void */ - public function includeAllClasses () { - if (is_object($this->classes)) { - // Load all classes - for ($idx = $this->classes->getIterator(); $idx->valid(); $idx->next()) { - // Load current class - //* DEBUG: */ print "Class=".$idx->current()."\n"; - require_once($idx->current()); - } - - // Re-initialize the classes list - $this->classes = new ArrayObject(); - } + public function includeClass ($className) { + // Create a name with prefix and suffix + $fileName = $this->prefix . $className . $this->suffix; + + // Now look it up in our index + if (isset($this->classes[$fileName])) { + // File is found so load it only once + //* DEBUG: */ echo "LOAD: ".$fileName." - Start
\n"; + require($this->classes[$fileName]); + //* DEBUG: */ echo "LOAD: ".$fileName." - End
\n"; + + // Count this include + $this->total++; + + // Mark this class as loaded + $this->loadedClasses[] = $this->classes[$fileName]; + + // Developer mode excludes caching (better debugging) + if (!defined('DEVELOPER')) { + // Reset cache + $this->classesCached = false; + } // END - if + } // END - if + } + + /** + * Includes all extra config files + * + * @return void + */ + private function includeExtraConfigs () { + // Run through all class names (should not be much) + foreach ($this->classes as $fileName => $fqfn) { + // Is this a config? + if (substr($fileName, 0, $this->prefixLen) == $this->prefix) { + // Then include it + require($fqfn); + + // Remove it from the list + unset($this->classes[$fileName]); + } // END - if + } // END - foreach } -} -// Initial load of core classes and the FrameworkDirectoryPointer class -require_once(sprintf("%sinc/classes/interfaces/class_FrameworkInterface%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension"))); -require_once(sprintf("%sinc/classes/main/class_BaseFrameworkSystem%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension"))); -require_once(sprintf("%sinc/classes/main/io/class_FrameworkDirectoryPointer%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension"))); + /** + * Getter for total include counter + * + * @return $total Total loaded include files + */ + public final function getTotal () { + return $this->total; + } -// Initialize the class loader -$loader = new ClassLoader(FrameworkConfiguration::getInstance()); + /** + * Getter for a printable list of included classes/interfaces/exceptions + * + * @param $includeList A printable include list + */ + public function getPrintableIncludeList () { + // Prepare the list + $includeList = ""; + foreach ($this->loadedClasses as $classFile) { + $includeList .= basename($classFile)."
\n"; + } // END - foreach + + // And return it + return $includeList; + } +} // [EOF] ?>