I am developing a new application from scratch and I need to autoload files recursively.
However, I need to use namespace like Zend Framework.
For example, LibraryName_Http_Request will load LibraryName/Http/Request.php file.
Whatsoever I’ve tried, I can only use LibraryName_Http_Request class if I name the file LibraryName_Http_Request.php.
I can’t figure out how to change my code so that i can load class files in the same Zend fashion…
Here is my code:
class Autoloader
{
public function __construct()
{
spl_autoload_register( array( $this, 'autoload' ) );
}
public function autoload( $class )
{
$iterator = new RecursiveDirectoryIterator( LIBRARY_PATH );
foreach( new RecursiveIteratorIterator( $iterator ) as $file=>$meta ) {
if( ( $class . '.php' ) === $meta->getFileName() ) {
if( file_exists( $file ) ) {
require_once $file;
}
break;
}
}
unset( $iterator, $file );
}
}
You should check out the PSR-0 which does what you want. You can find a link to PSR-0 loader implementation at the end of the recommendation.
Update: Since you are using PHP 5.2, the above loader doesn’t fully fit to your needs. Here is a simple autoloader I wrote based on PSR-0 without namespace support:
Then register the loader:
Now referencing
LibraryName_Http_Requestwill includeLibraryName/Http/Request.php.