【问题标题】:Restrict my spl_autoloader to only load classes in my namespace?限制我的 spl_autoloader 只加载我的命名空间中的类?
【发布时间】:2014-03-30 15:56:31
【问题描述】:

我刚刚开始在我的应用程序中使用自动加载器延迟加载,但我正在与命名空间发生冲突。自动加载器正在尝试加载诸如new DateTime() 之类的内容,但失败了。让我的自动加载器只针对我自己的命名空间类有什么技巧吗?

这是我目前拥有的代码。我怀疑这是一团糟,但我不知道如何纠正它:

<?php namespace RSCRM;
class Autoloader {
    static public function loader($className) {
        $filename = dirname(__FILE__) .'/'. str_replace("\\", '/', $className) . ".php";
        if (file_exists($filename)) {
            include_once($filename);
            if (class_exists($className)) {
                return TRUE;
            }
        }
        return FALSE;
    }
}
spl_autoload_register('\RSCRM\Autoloader::loader');

如果有人能指出一个可靠的例子,我们很高兴 RTM。

【问题讨论】:

    标签: php namespaces autoloader


    【解决方案1】:

    我使用的实际上是改编自用于对一些 AuraPHP 库进行单元测试的自动加载器:

    <?php
    spl_autoload_register(function ($class) {
    
        // a partial filename
        $part = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
    
        // directories where we can find classes
        $dirs = array(
            __DIR__ . DIRECTORY_SEPARATOR . 'src',
            __DIR__ . DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR . 'src',
            __DIR__ . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR . 'src',
        );
    
        // go through the directories to find classes
        foreach ($dirs as $dir) {
    
            $file = $dir . DIRECTORY_SEPARATOR . $part;
            if (is_readable($file)) {
                require $file;
                return;
            }
        }
    });
    

    只需确保“$dirs”值数组指向命名空间代码的根即可。

    您还可以查看 PSR-0 示例实现 (http://www.php-fig.org/psr/psr-0/)。

    您可能还想查看现有的自动加载器,例如 Aura.Autoload 或 Symfony 类加载器组件,尽管根据您的要求,这些可能有点矫枉过正。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-07-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多