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 - 2009 Roland Haeder, this is free software
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
29 * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
31 * - loadClasses rewritten to fix some notices
34 * ----------------------------------
38 * Instance of this class
40 private static $selfInstance = null;
45 private $cfg = array();
48 * Array with all classes
50 private $classes = array();
53 * List of loaded classes
55 private $loadedClasses = array();
58 * Suffix with extension for all class files
60 private $prefix = "class_";
63 * Suffix with extension for all class files
65 private $suffix = ".php";
68 * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
71 private $ignoreList = array();
74 * Debug this class loader? (true = yes, false = no)
76 private $debug = false;
79 * Wether the file list is cached or not
81 private $listCached = false;
84 * Wethe class content has been cached
86 private $classesCached = false;
89 * Filename for the list cache
91 private $listCacheFQFN = "";
94 * Cache for class content
96 private $classCacheFQFN = "";
99 * Counter for loaded include files
104 * The protected constructor. Please use the factory method below, or use
105 * getInstance() for singleton
109 protected function __construct () {
110 // Is Currently empty
114 * Our renamed factory method
116 * @param $cfgInstance Configuration class instance
119 public final static function createClassLoader (FrameworkConfiguration $cfgInstance) {
120 // Set configuration instance
121 $this->cfgInstance = $cfgInstance;
123 // Construct the FQFN for the cache
124 if (!defined('DEVELOPER')) {
125 $this->listCacheFQFN = $this->cfgInstance->readConfig('local_db_path') . "list-" . $this->cfgInstance->readConfig('app_name') . ".cache";
126 $this->classCacheFQFN = $this->cfgInstance->readConfig('local_db_path') . "class-" . $this->cfgInstance->readConfig('app_name') . ".cache";
129 // Set suffix and prefix from configuration
130 $this->suffix = $cfgInstance->readConfig('class_suffix');
131 $this->prefix = $cfgInstance->readConfig('class_prefix');
134 self::$selfInstance = $this;
136 // Skip here if no dev-mode
137 if (defined('DEVELOPER')) return;
139 // IS the cache there?
140 if (file_exists($this->listCacheFQFN)) {
142 $cacheContent = file_get_contents($this->listCacheFQFN);
145 $this->classes = unserialize($cacheContent);
147 // List has been restored from cache!
148 $this->listCached = true;
151 // Does the class cache exist?
152 if (file_exists($this->classCacheFQFN)) {
154 require($this->classCacheFQFN);
156 // Mark the class cache as loaded
157 $this->classesCached = true;
164 * @param $className Name of the class to load
167 public static function autoLoad ($className) {
168 // Try to include this class
169 self::getInstance()->includeClass($className);
173 * Getter for an instance of this class
175 * @return $selfInstance An instance of this class
177 public final static function getInstance () {
178 // Is the instance there?
179 if (is_null(self::$selfInstance)) {
181 self::$selfInstance = ClassLoader::createClassLoader(FrameworkConfiguration::getInstance());
184 // Return the instance
185 return self::$selfInstance;
189 * The destructor makes it sure all caches got flushed
193 public function __destruct () {
194 // Skip here if dev-mode
195 if (defined('DEVELOPER')) return;
197 // Skip here if already cached
198 if ($this->listCached === false) {
199 // Writes the cache file of our list away
200 $cacheContent = serialize($this->classes);
201 file_put_contents($this->listCacheFQFN, $cacheContent);
204 // Skip here if already cached
205 if ($this->classesCached === false) {
206 // Generate a full-cache of all classes
208 foreach ($this->loadedClasses as $fqfn) {
210 $cacheContent .= file_get_contents($fqfn);
214 file_put_contents($this->classCacheFQFN, $cacheContent);
219 * Fall-back method. Please replace loadClasses() with scanClassPath() !
221 * @param $basePath The relative base path to 'base_path' constant for all classes
222 * @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
225 * @todo Rewrite your apps to scanClassPath()
227 public function loadClasses ($basePath, array $ignoreList = array() ) {
228 // This outputs an ugly message because you need to change to scanClassPath
229 print __METHOD__." is deprecated. Use scanClassPath() to make this warning go away.<br />\n";
231 // Call our new method
232 $this->scanClassPath($basePath, $ignoreList);
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 // Is this file wanted?
282 //* DEBUG: */ echo "FOUND:{$fileName}<br />\n";
283 if ((!in_array($fileName, $this->ignoreList)) && (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
284 // Get the FQFN and add it to our class list
285 $fqfn = $entry->getRealPath();
286 //* DEBUG: */ echo "ADD: {$fileName}<br />\n";
287 $this->classes[$fileName] = $fqfn;
293 * Load extra config files
297 public function loadExtraConfigs () {
299 $oldPrefix = $this->prefix;
301 // Set new prefix (temporary!)
302 $this->prefix = "config-";
304 // Set base directory
305 $basePath = sprintf("%sinc/config/", $this->cfgInstance->readConfig('base_path'));
307 // Load all classes from the config directory
308 $this->scanClassPath($basePath);
310 // Include these extra configs now
311 $this->includeExtraConfigs();
313 // Set the prefix back
314 $this->prefix = $oldPrefix;
318 * Tries to find the given class in our list. This method ignores silently
319 * missing classes or interfaces. So if you use class_exists() this method
320 * does not interrupt your program.
322 * @param $className The class we shall load
325 public function includeClass ($className) {
326 // Create a name with prefix and suffix
327 $fileName = $this->prefix . $className . $this->suffix;
329 // Now look it up in our index
330 if ((isset($this->classes[$fileName])) && (!in_array($this->classes[$fileName], $this->loadedClasses))) {
331 // File is found and not loaded so load it only once
332 //* DEBUG: */ echo "LOAD: ".$fileName." - Start<br />\n";
333 require($this->classes[$fileName]);
334 //* DEBUG: */ echo "LOAD: ".$fileName." - End<br />\n";
336 // Count this include
339 // Mark this class as loaded
340 $this->loadedClasses[] = $this->classes[$fileName];
342 // Remove it from classes list
343 unset($this->classes[$fileName]);
345 // Developer mode excludes caching (better debugging)
346 if (!defined('DEVELOPER')) {
348 $this->classesCached = false;
354 * Includes all extra config files
358 private function includeExtraConfigs () {
359 // Run through all class names (should not be much)
360 foreach ($this->classes as $fileName => $fqfn) {
362 if (substr($fileName, 0, strlen($this->prefix)) == $this->prefix) {
366 // Remove it from the list
367 unset($this->classes[$fileName]);
373 * Getter for total include counter
375 * @return $total Total loaded include files
377 public final function getTotal () {
382 * Getter for a printable list of included classes/interfaces/exceptions
384 * @param $includeList A printable include list
386 public function getPrintableIncludeList () {
389 foreach ($this->loadedClasses as $classFile) {
390 $includeList .= basename($classFile)."<br />\n";