1

我正在从头开始开发一个新应用程序,我需要递归地自动加载文件。但是,我需要使用 Zend Framework 之类的命名空间。

例如,LibraryName_Http_Request将加载LibraryName/Http/Request.php文件。无论我尝试过什么,LibraryName_Http_Request如果我命名文件,我只能使用 class 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 回答