1

新しいアプリケーションを最初から開発していて、ファイルを再帰的に自動ロードする必要があります。ただし、ZendFrameworkのような名前空間を使用する必要があります。

たとえば、ファイルLibraryName_Http_RequestをロードしLibraryName/Http/Request.phpます。私が試したことは何でもLibraryName_Http_Request、ファイルに名前を付けた場合にのみクラスを使用できますLibraryName_Http_Request.php

同じZend方式でクラスファイルをロードできるようにコードを変更する方法がわかりません...

これが私のコードです:

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 );
    }

}
4

1 に答える 1

1

あなたはあなたが望むことをするPSR-0をチェックするべきです。推奨事項の最後に、PSR-0ローダーの実装へのリンクがあります。


更新: PHP 5.2を使用しているため、上記のローダーはニーズに完全には適合しません。これは、名前空間をサポートしないPSR-0に基づいて作成した単純なオートローダーです。

class SimpleClassLoader
{
    /**
     * Installs this class loader on the SPL autoload stack.
     */
    public function register()
    {
        spl_autoload_register(array($this, 'loadClass'));
    }

    /**
     * Uninstalls this class loader from the SPL autoloader stack.
     */
    public function unregister()
    {
        spl_autoload_unregister(array($this, 'loadClass'));
    }

    /**
     * Loads the given class or interface.
     *
     * @param string $className The name of the class to load.
     * @return void
     */
    public function loadClass($className)
    {
        require str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    }
}

次に、ローダーを登録します。

$loader = new SimpleClassLoader();
$loader->register();

これで、参照LibraryName_Http_Requestにはが含まれますLibraryName/Http/Request.php

于 2012-09-10T15:50:25.173 に答える