如何使用__autoload从多个目录加载类?

lau*_*kok 3 php oop pdo autoload

关注这个问题,似乎只需使用__autoload下面的代码即可解决重复问题,

function __autoload($class_name) 
{
    include AP_SITE."classes_1/class_".$class_name.".php";
}

$connection = new database_pdo(DSN,DB_USER,DB_PASS);
var_dump($connection);
Run Code Online (Sandbox Code Playgroud)

结果,

object(database_pdo)[1]
  protected 'connection' => 
    object(PDO)[2]
Run Code Online (Sandbox Code Playgroud)

但这只从一个目录加载类,其他目录呢?因为我将类分组在不同的目录中.如果我想从其他目录加载类,我会得到错误,

function __autoload($class_name) 
{
    include AP_SITE."classes_1/class_".$class_name.".php";
    include AP_SITE."classes_2/class_".$class_name.".php";
}
Run Code Online (Sandbox Code Playgroud)

信息,

警告:包括(C:/wamp/www/art_on_your_doorstep_2011_MVC/global/applications/CART/classes_2/class_database_pdo.php)[]:未能打开流:在没有这样的文件或目录...

这指的是这条线 - include AP_SITE."classes_2/class_".$class_name.".php";

所以,我的问题是 - 如何从多个目录中加载类__autoload

可能的解决方案:

function autoload_class_multiple_directory($class_name) 
{

    # List all the class directories in the array.
    $array_paths = array(
        'classes_1/', 
        'classes_2/'
    );

    # Count the total item in the array.
    $total_paths = count($array_paths);

    # Set the class file name.
    $file_name = 'class_'.strtolower($class_name).'.php';

    # Loop the array.
    for ($i = 0; $i < $total_paths; $i++) 
    {
        if(file_exists(AP_SITE.$array_paths[$i].$file_name)) 
        {
            include_once AP_SITE.$array_paths[$i].$file_name;
        } 
    }
}

spl_autoload_register('autoload_class_multiple_directory');
Run Code Online (Sandbox Code Playgroud)

hak*_*kre 5

您可以使用spl_autoload_register而不是单个__autoload功能注册多个自动加载功能.这是推荐的方式.

如果一个自动加载器能够加载该文件,则不会调用堆栈中的下一个.

但是,每个自动加载器只应加载它所用的类,因此您需要通过类名和/或来检查它is_file.通过classname通常会更好,因为如果应用程序增长,在文件系统上疯狂地尝试会给系统带来压力.

为了不重新发明轮子,您甚至可以使用已经存在的自动加载器,它能够在文件名调用上处理PSR-0标准.这些通常允许在基本目录上注册特定的命名空间.在您的情况下,这意味着您必须根据PSR-0约定重命名和组织文件.


快速解决方案(绑定到您的问题):

function __autoload($class_name) 
{
    $file = sprintf('%sclasses_1/class_%s.php', AP_SITE, $class_name);
    if (is_file($file))
    {
        include $file;
        return;
    }
    $file = sprintf('%sclasses_2/class_%s.php', AP_SITE, $class_name);
    if (is_file($file))
    {
        include $file;
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,已经存在代码重复(在您的代码中).因此,这应该只是一个临时解决方案,因为您最终会为要测试的每个目录提供越来越多的重复行.如果您考虑更改设计,请考虑PSR-0 shema,它有助于简化一个代码库,并且可以轻松地重用PHP世界中的其他现有组件.


function autoload_class_multiple_directory($class_name) 
{

    # List all the class directories in the array.
    $array_paths = array(
        'classes_1/', 
        'classes_2/'
    );

    foreach($array_paths as $path)
    {
        $file = sprintf('%s%s/class_%s.php', AP_SITE, $path, $class_name);
        if(is_file($file)) 
        {
            include_once $file;
        } 

    }
}

spl_autoload_register('autoload_class_multiple_directory');
Run Code Online (Sandbox Code Playgroud)