[dev] Autoloader suggestions
Michael M Slusarz
slusarz at horde.org
Thu Oct 30 16:44:23 UTC 2008
Having spent a good portion of last night trying to get autoload to
work with an application's library files, below find a patch to
Autoloader to attempt to overcome some shortcomings. The main
advantage of these changes is that we can do a call like this (e.g. in
IMP):
Horde_Autoloader::addClassPattern('/^IMP_/', IMP_BASE . '/lib/');
which will allow us to load things like 'IMP_Message' via autoloading.
Also uses include_once instead of include (prevents redefinition
errors if a library is attempted to be loaded manually after
autoloading) and exits immediately from the classPatterns loop if the
library file was successfully loaded.
diff --git a/Autoloader/lib/Horde/Autoloader.php
b/Autoloader/lib/Horde/Autoload index 9d414a4..ceb02ca 100644
--- a/Autoloader/lib/Horde/Autoloader.php
+++ b/Autoloader/lib/Horde/Autoloader.php
@@ -8,7 +8,7 @@ class Horde_Autoloader
* Patterns that match classes we can load.
* @var array
*/
- protected static $_classPatterns =3D array('/^Horde_/');
+ protected static $_classPatterns =3D array('/^Horde_/' => 'Horde/');
/**
* Autoload implementation automatically registered with
@@ -24,12 +24,21 @@ class Horde_Autoloader
*/
public static function loadClass($class)
{
- foreach (self::$_classPatterns as $pattern) {
- if (preg_match($pattern, $class)) {
- $file = str_replace(array('::', '_'), '/', $class) . '.php';
+ foreach (self::$_classPatterns as $pattern => $replace) {
+ $file = $class;
+
+ if (!is_null($replace)) {
+ $file = preg_replace($pattern, $replace, $file);
+ }
+
+ if (!is_null($replace) || preg_match($pattern, $file)) {
+ $file = str_replace(array('::', '_'), '/', $file) . '.php';
$oldErrorReporting = error_reporting(E_ALL ^ E_WARNING);
- include $file;
+ $res = include_once $file;
error_reporting($oldErrorReporting);
+ if ($res) {
+ return true;
+ }
}
}
}
@@ -66,10 +75,11 @@ class Horde_Autoloader
* Add a new class pattern.
*
* @param string $pattern The class pattern to add.
+ * @param string $replace The substitution pattern.
*/
- public static function addClassPattern($pattern)
+ public static function addClassPattern($pattern, $replace = null)
{
- self::$_classPatterns[] = $pattern;
+ self::$_classPatterns[$pattern] = $replace;
}
}
michael
--
___________________________________
Michael Slusarz [slusarz at horde.org]
More information about the dev
mailing list