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, 2010 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(), $configInstance renamed to $configInstance
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 * getInstance() for singleton
105 protected function __construct () {
106 // Is Currently empty
110 * Our renamed factory method
112 * @param $configInstance Configuration class instance
115 public static final function createClassLoader (FrameworkConfiguration $configInstance) {
116 // Get a new instance
117 $loaderInstance = new ClassLoader();
120 $loaderInstance->initLoader($configInstance);
122 // Return the prepared instance
123 return $loaderInstance;
127 * Initializes our loader class
129 * @param $configInstance Configuration class instance
132 protected function initLoader (FrameworkConfiguration $configInstance) {
133 // Set configuration instance
134 $this->configInstance = $configInstance;
136 // Construct the FQFN for the cache
137 if (!defined('DEVELOPER')) {
138 $this->listCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'list-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
139 $this->classCacheFQFN = $this->configInstance->getConfigEntry('local_db_path') . 'class-' . $this->configInstance->getConfigEntry('app_name') . '.cache';
142 // Set suffix and prefix from configuration
143 $this->suffix = $configInstance->getConfigEntry('class_suffix');
144 $this->prefix = $configInstance->getConfigEntry('class_prefix');
147 self::$selfInstance = $this;
149 // Skip here if no dev-mode
150 if (defined('DEVELOPER')) return;
152 // IS the cache there?
153 if (file_exists($this->listCacheFQFN)) {
155 $cacheContent = file_get_contents($this->listCacheFQFN);
158 $this->classes = unserialize($cacheContent);
160 // List has been restored from cache!
161 $this->listCached = true;
164 // Does the class cache exist?
165 if (file_exists($this->classCacheFQFN)) {
167 require($this->classCacheFQFN);
169 // Mark the class cache as loaded
170 $this->classesCached = true;
177 * @param $className Name of the class to load
180 public static function autoLoad ($className) {
181 // Try to include this class
182 self::getInstance()->includeClass($className);
186 * Getter for an instance of this class
188 * @return $selfInstance An instance of this class
190 public static final function getInstance () {
191 // Is the instance there?
192 if (is_null(self::$selfInstance)) {
194 self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getInstance());
197 // Return the instance
198 return self::$selfInstance;
202 * The destructor makes it sure all caches got flushed
206 public function __destruct () {
207 // Skip here if dev-mode
208 if (defined('DEVELOPER')) return;
210 // Skip here if already cached
211 if ($this->listCached === false) {
212 // Writes the cache file of our list away
213 $cacheContent = serialize($this->classes);
214 file_put_contents($this->listCacheFQFN, $cacheContent);
217 // Skip here if already cached
218 if ($this->classesCached === false) {
219 // Generate a full-cache of all classes
221 foreach ($this->loadedClasses as $fqfn) {
223 $cacheContent .= file_get_contents($fqfn);
227 file_put_contents($this->classCacheFQFN, $cacheContent);
232 * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
234 * @param $basePath The relative base path to 'base_path' constant for all classes
235 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
238 public function scanClassPath ($basePath, array $ignoreList = array() ) {
239 // Is a list has been restored from cache, don't read it again
240 if ($this->listCached === true) {
245 // Directories which our class loader ignores by default while
246 // deep-scanning the directory structure.
248 $ignoreList[] = '..';
249 $ignoreList[] = '.htaccess';
250 $ignoreList[] = '.svn';
252 // Keep it in class for later usage
253 $this->ignoreList = $ignoreList;
255 // Set base directory which holds all our classes, we should use an
256 // absolute path here so is_dir(), is_file() and so on will always
257 // find the correct files and dirs.
258 $basePath2 = realpath($basePath);
260 // If the basePath is false it is invalid
261 if ($basePath2 === false) {
262 /* @todo: Do not die here. */
263 die('Cannot read ' . $basePath . ' !');
266 $basePath = $basePath2;
269 // Get a new iterator
270 //* DEBUG: */ echo "<strong>Base path: {$basePath}</strong><br />\n";
271 $iterator = new RecursiveDirectoryIterator($basePath);
272 $recursive = new RecursiveIteratorIterator($iterator);
273 foreach ($recursive as $entry) {
274 // Get filename from iterator
275 $fileName = $entry->getFileName();
277 // Is this file wanted?
278 //* DEBUG: */ echo "FOUND:{$fileName}<br />\n";
279 if ((!in_array($fileName, $this->ignoreList)) && (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
280 // Get the FQFN and add it to our class list
281 $fqfn = $entry->getRealPath();
282 //* DEBUG: */ echo "ADD: {$fileName}<br />\n";
283 $this->classes[$fileName] = $fqfn;
289 * Load extra config files
293 public function loadExtraConfigs () {
295 $oldPrefix = $this->prefix;
297 // Set new prefix (temporary!)
298 $this->prefix = 'config-';
300 // Set base directory
301 $basePath = $this->configInstance->getConfigEntry('base_path') . 'inc/config/';
303 // Load all classes from the config directory
304 $this->scanClassPath($basePath);
306 // Include these extra configs now
307 $this->includeExtraConfigs();
309 // Set the prefix back
310 $this->prefix = $oldPrefix;
314 * Tries to find the given class in our list. This method ignores silently
315 * missing classes or interfaces. So if you use class_exists() this method
316 * does not interrupt your program.
318 * @param $className The class we shall load
321 public function includeClass ($className) {
322 // Create a name with prefix and suffix
323 $fileName = $this->prefix . $className . $this->suffix;
325 // Now look it up in our index
326 if ((isset($this->classes[$fileName])) && (!in_array($this->classes[$fileName], $this->loadedClasses))) {
327 // File is found and not loaded so load it only once
328 //* DEBUG: */ echo "LOAD: ".$fileName." - Start<br />\n";
329 require($this->classes[$fileName]);
330 //* DEBUG: */ echo "LOAD: ".$fileName." - End<br />\n";
332 // Count this include
335 // Mark this class as loaded
336 $this->loadedClasses[] = $this->classes[$fileName];
338 // Remove it from classes list
339 unset($this->classes[$fileName]);
341 // Developer mode excludes caching (better debugging)
342 if (!defined('DEVELOPER')) {
344 $this->classesCached = false;
350 * Includes all extra config files
354 private function includeExtraConfigs () {
355 // Run through all class names (should not be much)
356 foreach ($this->classes as $fileName => $fqfn) {
358 if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
362 // Remove it from the list
363 unset($this->classes[$fileName]);
369 * Getter for total include counter
371 * @return $total Total loaded include files
373 public final function getTotal () {
378 * Getter for a printable list of included classes/interfaces/exceptions
380 * @param $includeList A printable include list
382 public function getPrintableIncludeList () {
385 foreach ($this->loadedClasses as $classFile) {
386 $includeList .= basename($classFile)."<br />\n";