3 * This class loads class include files with a specific prefix and suffix
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * ----------------------------------
26 * - Constructor is now empty and factory method 'createClassLoader' is created
27 * - renamed loadClasses to scanClassPath
28 * - Added initLoader()
30 * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
32 * - loadClasses rewritten to fix some notices
35 * ----------------------------------
39 * Instance of this class
41 private static $selfInstance = NULL;
44 * Array with all classes
46 private $classes = array();
49 * List of loaded classes
51 private $loadedClasses = array();
54 * Suffix with extension for all class files
56 private $prefix = 'class_';
59 * Suffix with extension for all class files
61 private $suffix = '.php';
64 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
67 private $ignoreList = array();
70 * Debug this class loader? (true = yes, false = no)
72 private $debug = false;
75 * Wether the file list is cached or not
77 private $listCached = false;
80 * Wethe class content has been cached
82 private $classesCached = false;
85 * Filename for the list cache
87 private $listCacheFQFN = '';
90 * Cache for class content
92 private $classCacheFQFN = '';
95 * Counter for loaded include files
100 * The protected constructor. Please use the factory method below, or use
101 * getSelfInstance() for singleton
105 protected function __construct () {
106 // Is currently empty
110 * The destructor makes it sure all caches got flushed
114 public function __destruct () {
115 // Skip here if dev-mode
116 if (defined('DEVELOPER')) {
120 // Skip here if already cached
121 if ($this->listCached === false) {
122 // Writes the cache file of our list away
123 $cacheContent = serialize($this->classes);
124 file_put_contents($this->listCacheFQFN, $cacheContent);
127 // Skip here if already cached
128 if ($this->classesCached === false) {
129 // Generate a full-cache of all classes
131 foreach ($this->loadedClasses as $fqfn) {
133 $cacheContent .= file_get_contents($fqfn);
137 file_put_contents($this->classCacheFQFN, $cacheContent);
142 * Our renamed factory method
144 * @param $configInstance Configuration class instance
147 public static final function createClassLoader (FrameworkConfiguration $configInstance) {
148 // Get a new instance
149 $loaderInstance = new ClassLoader();
152 $loaderInstance->initLoader($configInstance);
154 // Return the prepared instance
155 return $loaderInstance;
159 * Initializes our loader class
161 * @param $configInstance Configuration class instance
164 protected function initLoader (FrameworkConfiguration $configInstance) {
165 // Set configuration instance
166 $this->configInstance = $configInstance;
168 // Construct the FQFN for the cache
169 if (!defined('DEVELOPER')) {
170 $this->listCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
171 $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
174 // Set suffix and prefix from configuration
175 $this->suffix = $configInstance->getConfigEntry('class_suffix');
176 $this->prefix = $configInstance->getConfigEntry('class_prefix');
179 self::$selfInstance = $this;
181 // Skip here if no dev-mode
182 if (defined('DEVELOPER')) {
186 // IS the cache there?
187 if (file_exists($this->listCacheFQFN)) {
189 $cacheContent = file_get_contents($this->listCacheFQFN);
192 $this->classes = unserialize($cacheContent);
194 // List has been restored from cache!
195 $this->listCached = true;
198 // Does the class cache exist?
199 if (file_exists($this->classCacheFQFN)) {
201 require($this->classCacheFQFN);
203 // Mark the class cache as loaded
204 $this->classesCached = true;
211 * @param $className Name of the class to load
214 public static function autoLoad ($className) {
215 // Try to include this class
216 self::getSelfInstance()->includeClass($className);
220 * Singleton getter for an instance of this class
222 * @return $selfInstance A singleton instance of this class
224 public static final function getSelfInstance () {
225 // Is the instance there?
226 if (is_null(self::$selfInstance)) {
228 self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getSelfInstance());
231 // Return the instance
232 return self::$selfInstance;
236 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
238 * @param $basePath The relative base path to 'base_path' constant for all classes
239 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
242 public function scanClassPath ($basePath, array $ignoreList = array() ) {
243 // Is a list has been restored from cache, don't read it again
244 if ($this->listCached === true) {
249 // Directories which our class loader ignores by default while
250 // deep-scanning the directory structure.
252 $ignoreList[] = '..';
253 $ignoreList[] = '.htaccess';
254 $ignoreList[] = '.svn';
256 // Keep it in class for later usage
257 $this->ignoreList = $ignoreList;
259 // Set base directory which holds all our classes, we should use an
260 // absolute path here so is_dir(), is_file() and so on will always
261 // find the correct files and dirs.
262 $basePath2 = realpath($basePath);
264 // If the basePath is false it is invalid
265 if ($basePath2 === false) {
266 /* @todo: Do not die here. */
267 die('Cannot read ' . $basePath . ' !');
270 $basePath = $basePath2;
273 // Get a new iterator
274 //* DEBUG: */ echo "<strong>Base path: {$basePath}</strong><br />\n";
275 $iterator = new RecursiveDirectoryIterator($basePath);
276 $recursive = new RecursiveIteratorIterator($iterator);
277 foreach ($recursive as $entry) {
278 // Get filename from iterator
279 $fileName = $entry->getFileName();
281 // Get the FQFN and add it to our class list
282 $fqfn = $entry->getRealPath();
284 // Is this file wanted?
285 //* DEBUG: */ echo "FOUND:{$fileName}<br />\n";
286 if ((!in_array($fileName, $this->ignoreList)) && (filesize($fqfn) > 100) && (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
287 //* DEBUG: */ echo "ADD: {$fileName}<br />\n";
288 // Add it to the list
289 $this->classes[$fileName] = $fqfn;
295 * Load extra config files
299 public function loadExtraConfigs () {
301 $oldPrefix = $this->prefix;
303 // Set new prefix (temporary!)
304 $this->prefix = 'config-';
306 // Set base directory
307 $basePath = $this->configInstance->getConfigEntry('base_path') . 'inc/config/';
309 // Load all classes from the config directory
310 $this->scanClassPath($basePath);
312 // Include these extra configs now
313 $this->includeExtraConfigs();
315 // Set the prefix back
316 $this->prefix = $oldPrefix;
320 * Tries to find the given class in our list. This method ignores silently
321 * missing classes or interfaces. So if you use class_exists() this method
322 * does not interrupt your program.
324 * @param $className The class we shall load
327 public function includeClass ($className) {
328 // Create a name with prefix and suffix
329 $fileName = $this->prefix . $className . $this->suffix;
331 // Now look it up in our index
332 if ((isset($this->classes[$fileName])) && (!in_array($this->classes[$fileName], $this->loadedClasses))) {
333 // File is found and not loaded so load it only once
334 //* DEBUG: */ echo "LOAD: ".$fileName." - Start<br />\n";
335 require($this->classes[$fileName]);
336 //* DEBUG: */ echo "LOAD: ".$fileName." - End<br />\n";
338 // Count this include
341 // Mark this class as loaded
342 $this->loadedClasses[] = $this->classes[$fileName];
344 // Remove it from classes list
345 unset($this->classes[$fileName]);
347 // Developer mode excludes caching (better debugging)
348 if (!defined('DEVELOPER')) {
350 $this->classesCached = false;
356 * Includes all extra config files
360 private function includeExtraConfigs () {
361 // Run through all class names (should not be much)
362 foreach ($this->classes as $fileName => $fqfn) {
364 if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
368 // Remove it from the list
369 unset($this->classes[$fileName]);
375 * Getter for total include counter
377 * @return $total Total loaded include files
379 public final function getTotal () {
384 * Getter for a printable list of included classes/interfaces/exceptions
386 * @param $includeList A printable include list
388 public function getPrintableIncludeList () {
391 foreach ($this->loadedClasses as $classFile) {
392 $includeList .= basename($classFile)."<br />\n";