php命名空间自动加载目录

php命名空间自动加载目录,php,namespaces,spl-autoload-register,Php,Namespaces,Spl Autoload Register,我有这样一个类结构树: - garcha/ | - html/ | Tag.php | VTag.php | etc.. 工作原理:通过spl_自动加载_寄存器自动加载 无法工作: 要实现它,不需要:我不想逐行编写每个类文件的use语句,而是指向类目录并使用没有父命名空间的类 use garcha\html\Tag; use garcha\html\VTag; ... 我不喜欢这种方式,因为它很无聊,需要更多的时间,灵活性较差。您可能会更改文件结构、

我有这样一个类结构树:

- garcha/
|   - html/
|       Tag.php
|       VTag.php
|       etc..
工作原理:通过spl_自动加载_寄存器自动加载

无法工作:

要实现它,不需要:我不想逐行编写每个类文件的use语句,而是指向类目录并使用没有父命名空间的类

use garcha\html\Tag;
use garcha\html\VTag;
... 
我不喜欢这种方式,因为它很无聊,需要更多的时间,灵活性较差。您可能会更改文件结构、类名等

简而言之:我正在尝试自动加载带名称空间的类目录,并使用其中具有非限定名称的类

自动加载器功能:

添加路径:

自动加载工作,问题是如何处理

use garcha\html; // class directory
并使用不带html的类


您可以尝试不同的解决方案:

首先:可以在pathes变量中添加garcha/html,如::addPath'garcha/html'

第二:尝试在自动加载器中使用以下代码

foreach (glob("garcha/*.php") as $filename)
{
    require_once $filename;
}
glob基本上会匹配所有以.php结尾的文件,然后您可以使用它们将它们添加到pathes变量中,或者只包含它们

注意:您需要稍微修改您的自动加载器以在其中使用上面的循环

编辑: 试试这个:

public static function load($class) 
{
    // check if given class is directory
    if (is_dir($class)) {
       // if given class is directory, load all php files under it
       foreach(glob($class . '/*.php') as $filePath) {
          if (is_file($filePath)) 
          {
             require_once $filePath;

             return true;
          }
       }
    } else {
       // otherwise load individual files (your current code)
       /* Your current code to load individual class */
    }

    return false;
}

您自己是什么::$paths设置为为什么不使用完整的命名空间路径?如果以后更改路径,则必须更改它,请使用或not@GGio我已经更新了question@Machavity假设该目录中有10多个类,为每个类写10行并不酷:/@GeorgeGarchagudashvili可能会在自动加载器中添加html以从/htmltanks加载所有类,但这不是我想要的,因为还会有garcha\validator、garcha\database等。。包含其中的所有文件似乎不是一个好主意。此外,它也不值得,因为我将只使用html\Tag或Database\Connection。如果在不加载所有文件的情况下无法完成所需的解决方案,我将继续使用当前可用性。非常感谢,似乎这将是唯一的解决方案,或者为每个问题编写使用声明class@GeorgeGarchagudashvili我将此设置为书签,以防有人发布有效的解决方案。我也想在我的应用程序中使用它:。阿坝申慈გენაცვალე, მადლობა
AutoLoader::addPath(BASE_PATH.DIRECTORY_SEPARATOR.'vendor');
use garcha\html; // class directory
$tag = new Tag('p'); // not $tag = new html\Tag('p');
foreach (glob("garcha/*.php") as $filename)
{
    require_once $filename;
}
public static function load($class) 
{
    // check if given class is directory
    if (is_dir($class)) {
       // if given class is directory, load all php files under it
       foreach(glob($class . '/*.php') as $filePath) {
          if (is_file($filePath)) 
          {
             require_once $filePath;

             return true;
          }
       }
    } else {
       // otherwise load individual files (your current code)
       /* Your current code to load individual class */
    }

    return false;
}