note 63943 deleted from language.oop5.autoload by bjori
| From: | bjori@php.net | Date: | Tue, 04 Apr 2006 18:10:39 +0000 |
| Subject: | note 63943 deleted from language.oop5.autoload by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-107321@lists.php.net to get a copy of this message | ||
Note Submitter: mel dot boyce at gmail dot com
Reason: useless
----
Here's some code for a rules based autoloader I recently built and thought may be of use to
someone else. The main rule here is for loading classes from a CoreLib/ directory. A class might be
named something like 'CoreState' which would require the file
'CoreLib/core.state.class.php'. Simply add your own rules (PCRE RegExps) to the array and
away you go.
The only missing functionality I can think of is for using the same pattern for looking in multiple
directories for the source file. Because I'm using the pattern as the key for the rules hash,
reusing a pattern will overwrite any previous rules with that pattern.
function __autoload($class_name) {
$rules = array(
"/Core(.+)/e" =>
"'CoreLib/core.'.strtolower('\\1').'.class.php'",
"/Smarty/" => "CoreLib/3p/Smarty/Smarty.class.php"
);
foreach ($rules as $patt => $repl) {
$count = 0;
$class_file = preg_replace($patt,$repl,$class_name,-1,$count);
if ($count > 0 && file_exists($class_file)) {
require_once($class_file);
return true;
}
}
// place some error trapping here if you think it's important
}