Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php SPL自动加载最佳实践_Php_Spl_Autoloader_Spl Autoloader - Fatal编程技术网

Php SPL自动加载最佳实践

Php SPL自动加载最佳实践,php,spl,autoloader,spl-autoloader,Php,Spl,Autoloader,Spl Autoloader,在服务器端的include_路径中,我在“/usr/share/pear/”中引用了一个pear目录。在我的应用程序中,我包含了一个公共库中的文件,它位于“/usr/share/pear/library/”中,带有require\u once“library/file.php” 我最近开始使用spl autoloader,我注意到在loader函数中,您必须确定包含文件的逻辑。我做这件事的第一个方法是尝试包含一个文件,并用@抑制它,看它是否会失败,例如,@include'library/file

在服务器端的include_路径中,我在“/usr/share/pear/”中引用了一个pear目录。在我的应用程序中,我包含了一个公共库中的文件,它位于“/usr/share/pear/library/”中,带有
require\u once“library/file.php”

我最近开始使用spl autoloader,我注意到在loader函数中,您必须确定包含文件的逻辑。我做这件事的第一个方法是尝试包含一个文件,并用
@
抑制它,看它是否会失败,例如,
@include'library/file.php'
然而,我想主要是因为我读了很多关于
@
是一种不好的做法的书,我决定自己手动完成这项工作,通过使用
路径分隔符
来分解
get\u include\u path
,看看目录是否是我想要的,然后执行一个
文件\u并包含它

像这样:

function classLoader( $class ) {
    $paths = explode( PATH_SEPARATOR, get_include_path() );
    $file = SITE_PATH . 'classes' . DS . $class . '.Class.php';
    if ( file_exists( $file) == false ) 
    {
        $exists = false;
        foreach ( $paths as $path ) 
        {
            $tmp = $path . DS . 'library' . DS . 'classes' . DS . $class . '.Class.php';
            if ( file_exists ( $tmp ) ) 
            {
            $exists = true;
            $file = $tmp;
            }
        }
        if ( !$exists ) { return false; }
    }
    include $file;
}

spl_autoload_register('classLoader');

我走错路线了吗?我应该只是做了
@include
业务,还是朝着正确的方向做

我个人使用

function autoload($class) {
    /* transform class name into filename ... */
    include $class;
}
即使没有@也可以简化调试(在生产中关闭/记录错误)

您可能还对PHP开发者列表上的相关讨论感兴趣:

有一件事很有趣,就是将整个类文件列表缓存在内存中,这样它就不会在每次请求类时都对文件进行磁盘搜索

本质上,您在
\uuuu autoload()
中声明了一个static,该static包含所有类文件的数组,这些类文件由将导致加载它们的类索引。例如,代码将使用Dir或
glob()
生成此静态数组:

$class_files = array(
  'user' => '/var/www/htdocs/system/classes/user.class.php',
);
然后,只需包含
$class\u文件[$class]
即可获得正确的文件。这很好,速度也很快,因为它一次从磁盘获取目录,而不是在每次引用新类时生成列表或搜索特定的文件名。(你会惊讶于它会带来多大的速度差异。)

如果类名不是数组中的键,则可以引发自定义异常或生成要返回的存根/模拟类。此外,如果您查看Habari系统自动加载程序,您将看到Habari在自动加载的类中实现了
\uu static()
,这类似于静态类的构造函数


include_once()
是要避免的,如果您已检查文件是否包含,则不需要使用
@
操作符。

spl自动加载不是更实用和现代的方法吗?或者它们基本上是一样的?