I say (mostly) because I’m sure someone can come up with a scheme to break this, but it should be flexible enough to cover 80% of cases, including PSR-0, and if you can come up with a way to store classes this can’t handle you can write your own autoloader.
Well, if this one is writable…
This at the moment is a thought exercise.
The factory of the autoloader is given the directory or directories to search for files. Using [fphp]glob[/fphp] it slurps in all files matching a pattern, default *.php (though *.class.php or *.inc will likely be popular).
Then, one file at a time, it uses regex to find the namespace declaration of the file, if any. If there are multiple namespaces (the programmer used the less often invoked namespace { } construction ) the file is divided into it’s component namespaces. Again, using regex, we search for the pattern /class $ /. Each class is appended to the namespace it is found in and added to an array.
If duplicate classes are found the autoloader fails with an error (this is one of the cases in the 20% I’m not touching) telling you which two files have identical classes.
? Or would it be better to continue but to refuse to autoload either class ?
? Or proceed, first class found only ?
In all cases, an error E_USER_WARNING at least should be raised, if not an exception thrown or fatal error.
Once all the classes are found, the array is passed to the actual autoloader. This object needs to be cachable to be effective, as no sane live system would be responsive with that much file scanning occurring each page load.
Note that in the keys the class / namespace names will be passed stored as typed. When the autoloader compares it will make a case sensitive check first, but since PHP doesn’t require class identifiers and namespaces to be case sensitive it will make a second case insensitive check. If it finds the class this way it will throw an E_STRICT
? would it be better to forego doing that and just store the class / namespace paths under strtolower() and make all the checks case insensitive?
I have a working autoloader that mostly works this way - using a file system scan to find class files - but it doesn’t analyze file contents and depends on the convention that namespace significant directories will have a .ns extension. The system above however is foolproof enough to deal with the poorly thought out PSR-0 standard and also load most class hives that don’t follow the standard.
(The reason I call out that standard as poorly thought out is there is no way to determine, from the file’s position in the file structure, what the class name is going to be - yet changing a file’s position in that structure forces you to edit the class’ name. It’s a double whammy of code inflexibility for no real gain).