LeanCloud中的PHP autoload

2016-09-16  本文已影响41人  赵小楠

官方是这么说的 自动加载类

很多开发者写面向对象的应用程序时对每个类的定义建立一个 PHP 源文件。一个很大的烦恼是不得不在每个脚本开头写一个长长的包含文件列表(每个类一个文件)。 在 PHP 5 中,不再需要这样了。可以定义一个 __autoload() 函数, 它会在试图使用尚未被定义的类时自动调用。通过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

最新的发展情况是

tip:
spl_autoload_register() 提供了一种更加灵活的方式来实现类的自动加载。因此,不再建议使用 __autoload()函数,在以后的版本中它可能被弃用。

一点想法

<pre>
相较于.Net的Namespace, PHP的namespace除了用来方便引用class,组织代码结构,也用来提供需要文件的路径查找。
脚本语言与编译型语言的差异可见一斑。
</pre>

下面是LeanCloud的autoload
主要思路是通过$classname 拆分出是否是leancloud的class,并通过分解namespace classname得到php文件的路径,并require到项目中来。

/**
 * Enable autoload
 * 
 * Require this file to enable autoload SDK classes on the fly. If you're
 * using composer, it should be required automatically.
 *
 * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
 *
 * @param string $class 完整的class名字.
 * @return void
 */

spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'LeanCloud\\';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/LeanCloud/';

    // does the class use the namespace prefix?
    /* 
      strlen 获取leanCloud字符的长度,
      strncmp **判断两个字符串前n个字符是否相等,区分大小写**
      比较截取长度为$len的两个字符串是否一致 
    */
    
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace
    // namespace separators with directory separators in the relative
    // class name, append with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

扩展阅读
require()、require_once()、include()和include_once()的区别

上一篇下一篇

猜你喜欢

热点阅读