PHP/Composer是如何加载一个类的

902 阅读5分钟
原文链接: www.robberphex.com

PHP/composer开发中,我们只需要require ‘vendor/autoload.php’,然后就可以直接使用各种类了。那么这些类是如何加载的呢?其中有没有什么可以优化的点呢?

概览

PHP/composer下,类的加载主要到如下部分(还没有包括各个部分的初始化逻辑):

  1. PHP中zend_lookup_class_ex
  2. |-> EG(class_table)
  3. |-> spl_autoload_call
  4. |-> Composer\Autoload\ClassLoader::loadClass
  5. |-> findFile
  6. |-> class map lookup
  7. |-> PSR-4 lookup
  8. |-> PSR-0 lookup

PHP的类加载

首先,PHP在运行的时候,需要一个类,是通过zend_lookup_class_ex来找到这个类的相关信息的。

zend_lookup_class_ex查找类的主要逻辑如下(假设类名字放到变量lc_name中):

  1. ZEND_API zend_class_entry *zend_lookup_class_ex(zend_string *name, const zval *key, int use_autoload) /* {{{ */
  2. {
  3. // 1. 类名字转化为小写
  4. if (ZSTR_VAL(name)[0] == '\\') {
  5. lc_name = zend_string_alloc(ZSTR_LEN(name) - 1, 0);
  6. zend_str_tolower_copy(ZSTR_VAL(lc_name), ZSTR_VAL(name) + 1, ZSTR_LEN(name) - 1);
  7. } else {
  8. lc_name = zend_string_tolower(name);
  9. }
  10. // 2. 直接在class_table中查找
  11. ce = zend_hash_find_ptr(EG(class_table), lc_name);
  12. if (ce) {
  13. if (!key) {
  14. zend_string_release(lc_name);
  15. }
  16. return ce;
  17. }
  18. // 3. 如果没有autoload_func,则注册默认的__autoload
  19. if (!EG(autoload_func)) {
  20. zend_function *func = zend_hash_str_find_ptr(EG(function_table), ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1);
  21. if (func) {
  22. EG(autoload_func) = func;
  23. } else {
  24. if (!key) {
  25. zend_string_release(lc_name);
  26. }
  27. return NULL;
  28. }
  29. }
  30. // 4. 加载ACLASS的过程中,又加载ACLASS,递归加载,直接找不到类
  31. if (zend_hash_add_empty_element(EG(in_autoload), lc_name) == NULL) {
  32. if (!key) {
  33. zend_string_release(lc_name);
  34. }
  35. return NULL;
  36. }
  37. // 5. 调用autoload_func
  38. ZVAL_STR_COPY(&fcall_info.function_name, EG(autoload_func)->common.function_name);
  39. fcall_info.symbol_table = NULL;
  40. zend_exception_save();
  41. if ((zend_call_function(&fcall_info, &fcall_cache) == SUCCESS) && !EG(exception)) {
  42. ce = zend_hash_find_ptr(EG(class_table), lc_name);
  43. }
  44. zend_exception_restore();
  45. if (!key) {
  46. zend_string_release(lc_name);
  47. }
  48. return ce;
  49. }
  1. lc_name转化成小写(这说明PHP中类名字不区分大小写)
  2. 然后在EG(class_table)找,如果找到,直接返回(我们自己注册的类,扩展注册的类都是这样找到的)
  3. 然后查看EG(autoload_func) ,如果没有则将__autoload注册上(值得注意的是,如果注册了EG(autoload_func),则不会走__autoload)
  4. 通过EG(in_autoload)判断是否递归加载了(EG(in_autoload)是一个栈,记载了那些类正在被autoload加载)
  5. 然后调用EG(autoload_func),并返回类信息

SPL扩展注册

刚刚可以看到,PHP只会调用EG(autoload_func),根本没有什么SPL的事情,那么SPL是如何让PHP调用自己的类加机制的呢?

首先,我去找SPL扩展的MINIT过程,结果发现其中并没有相关的逻辑。

出乎我的意料,这个注册过程在spl_autoload_register中完成:

  1. PHP_FUNCTION(spl_autoload_register)
  2. {
  3. // 已经将SPL注册到PHP了,且当前用户要注册到spl的autoload函数已经注册,则跳过
  4. if (SPL_G(autoload_functions) && zend_hash_exists(SPL_G(autoload_functions), lc_name)) {
  5. if (!Z_ISUNDEF(alfi.closure)) {
  6. Z_DELREF_P(&alfi.closure);
  7. }
  8. goto skip;
  9. }
  10. // 如果必要的话,初始化SPL_G(autoload_functions)
  11. if (!SPL_G(autoload_functions)) {
  12. ALLOC_HASHTABLE(SPL_G(autoload_functions));
  13. zend_hash_init(SPL_G(autoload_functions), 1, NULL, autoload_func_info_dtor, 0);
  14. }
  15. // 如果之前已经注册了spl_autoload,那就将spl_autoload转移到autoload_functions中
  16. spl_func_ptr = zend_hash_str_find_ptr(EG(function_table), "spl_autoload", sizeof("spl_autoload") - 1);
  17. if (EG(autoload_func) == spl_func_ptr) { /* registered already, so we insert that first */
  18. autoload_func_info spl_alfi;
  19. spl_alfi.func_ptr = spl_func_ptr;
  20. ZVAL_UNDEF(&spl_alfi.obj);
  21. ZVAL_UNDEF(&spl_alfi.closure);
  22. spl_alfi.ce = NULL;
  23. zend_hash_str_add_mem(SPL_G(autoload_functions), "spl_autoload", sizeof("spl_autoload") - 1,
  24. &spl_alfi, sizeof(autoload_func_info));
  25. if (prepend && SPL_G(autoload_functions)->nNumOfElements > 1) {
  26. /* Move the newly created element to the head of the hashtable */
  27. HT_MOVE_TAIL_TO_HEAD(SPL_G(autoload_functions));
  28. }
  29. }
  30. // 将用户要注册的函数,即lc_name,放到autoload_functions中
  31. if (zend_hash_add_mem(SPL_G(autoload_functions), lc_name, &alfi, sizeof(autoload_func_info)) == NULL) {
  32. if (obj_ptr && !(alfi.func_ptr->common.fn_flags & ZEND_ACC_STATIC)) {
  33. Z_DELREF(alfi.obj);
  34. }
  35. if (!Z_ISUNDEF(alfi.closure)) {
  36. Z_DELREF(alfi.closure);
  37. }
  38. if (UNEXPECTED(alfi.func_ptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) {
  39. zend_string_release(alfi.func_ptr->common.function_name);
  40. zend_free_trampoline(alfi.func_ptr);
  41. }
  42. }
  43. if (prepend && SPL_G(autoload_functions)->nNumOfElements > 1) {
  44. /* Move the newly created element to the head of the hashtable */
  45. HT_MOVE_TAIL_TO_HEAD(SPL_G(autoload_functions));
  46. }
  47. skip:
  48. zend_string_release(lc_name);
  49. }
  50. // 根据autoload_functions的值,决定向PHP注册spl_autoload_call还是spl_autoload
  51. if (SPL_G(autoload_functions)) {
  52. EG(autoload_func) = zend_hash_str_find_ptr(EG(function_table), "spl_autoload_call", sizeof("spl_autoload_call") - 1);
  53. } else {
  54. EG(autoload_func) = zend_hash_str_find_ptr(EG(function_table), "spl_autoload", sizeof("spl_autoload") - 1);
  55. }
  56. RETURN_TRUE;
  57. }

在composer环境下,这个函数的功能就是,将用户的autoload函数放到SPL_G(autoload_functions)中,且将spl_autoload_call注册到PHP中。

这样,PHP在找一个类的时候,就会调用spl_autoload_call了。

spl_autoload_call逻辑

spl_autoload_call的逻辑很简单:

  1. PHP_FUNCTION(spl_autoload_call)
  2. {
  3. if (SPL_G(autoload_functions)) {
  4. HashPosition pos;
  5. zend_ulong num_idx;
  6. int l_autoload_running = SPL_G(autoload_running);
  7. SPL_G(autoload_running) = 1;
  8. lc_name = zend_string_alloc(Z_STRLEN_P(class_name), 0);
  9. zend_str_tolower_copy(ZSTR_VAL(lc_name), Z_STRVAL_P(class_name), Z_STRLEN_P(class_name));
  10. zend_hash_internal_pointer_reset_ex(SPL_G(autoload_functions), &pos);
  11. // 遍历之前注册的autoload_functions
  12. while (zend_hash_get_current_key_ex(SPL_G(autoload_functions), &func_name, &num_idx, &pos) == HASH_KEY_IS_STRING) {
  13. alfi = zend_hash_get_current_data_ptr_ex(SPL_G(autoload_functions), &pos);
  14. if (UNEXPECTED(alfi->func_ptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) {
  15. zend_function *copy = emalloc(sizeof(zend_op_array));
  16. memcpy(copy, alfi->func_ptr, sizeof(zend_op_array));
  17. copy->op_array.function_name = zend_string_copy(alfi->func_ptr->op_array.function_name);
  18. // 调用autoload_function
  19. zend_call_method(Z_ISUNDEF(alfi->obj)? NULL : &alfi->obj, alfi->ce, ©, ZSTR_VAL(func_name), ZSTR_LEN(func_name), retval, 1, class_name, NULL);
  20. } else {
  21. zend_call_method(Z_ISUNDEF(alfi->obj)? NULL : &alfi->obj, alfi->ce, &alfi->func_ptr, ZSTR_VAL(func_name), ZSTR_LEN(func_name), retval, 1, class_name, NULL);
  22. }
  23. zend_exception_save();
  24. if (retval) {
  25. zval_ptr_dtor(retval);
  26. retval = NULL;
  27. }
  28. // 如果调用结束之后,能在class_table找到类,则返回
  29. if (zend_hash_exists(EG(class_table), lc_name)) {
  30. break;
  31. }
  32. zend_hash_move_forward_ex(SPL_G(autoload_functions), &pos);
  33. }
  34. zend_exception_restore();
  35. zend_string_free(lc_name);
  36. SPL_G(autoload_running) = l_autoload_running;
  37. } else {
  38. /* do not use or overwrite &EG(autoload_func) here */
  39. zend_call_method_with_1_params(NULL, NULL, NULL, "spl_autoload", NULL, class_name);
  40. }
  41. }
  1. 判断SPL_G(autoload_functions)存在
  2. 依次调用autoload_functions
  3. 如果调用完成后,这个类存在了,那就返回

至此,SPL的部分已经讲完了。我们来看看composer做了什么。

composer注册autoload

composer的autoload注册在 ‘vendor/autoload.php’ 中完成,这个文件完成了两件事:

  1. include vendor/composer/autoload_real.php
  2. 调用ComposerAutoloaderInit<rand_id>::getLoader()

vendor/composer/autoload_real.php仅仅定义了ComposerAutoloaderInit<rand_id>类和composerRequire<rand_id>函数。

<rand_id>是类似id一样的东西,确保要加载多个composer的autoload的时候不会冲突。composerRequire<rand_id>则是为了避免ComposerAutoloader require文件的时候,文件修改了ComposerAutoloader的东西。

接下来我们关注下ComposerAutoloaderInit<rand_id>::getLoader()做了哪些事情。

这个类的loader只会初始化一次,第二次是直接返回已经存在的loader了:

  1. if (null !== self::$loader) {
  2. return self::$loader;
  3. }

如果是第一次调用,先注册['ComposerAutoloaderInit<rand_id>', 'loadClassLoader'],然后new一个\Composer\Autoload\ClassLoader 作为$loader,然后立马取消注册loadClassLoader

也就是说['ComposerAutoloaderInit<rand_id>', 'loadClassLoader']的唯一作用就是加载\Composer\Autoload\ClassLoader。

接下来就是在ComposerAutoloaderInit<rand_id>::getLoader()初始刚刚拿到的$loader了:

  1. // autoload_namespaces.php里面放的是PSR-0
  2. $map = require __DIR__ . '/autoload_namespaces.php';
  3. foreach ($map as $namespace => $path) {
  4. $loader->set($namespace, $path);
  5. }
  6. // autoload_psr4.php里面放的是PSR-4注册的
  7. $map = require __DIR__ . '/autoload_psr4.php';
  8. foreach ($map as $namespace => $path) {
  9. $loader->setPsr4($namespace, $path);
  10. }
  11. // autoload_classmap.php放的是classmap注册的
  12. $classMap = require __DIR__ . '/autoload_classmap.php';
  13. if ($classMap) {
  14. $loader->addClassMap($classMap);
  15. }
  16. // ……
  17. // 将[$loader, 'loadClass']注册到spl中
  18. $loader->register(true);
  19. // ……
  20. // autoload_files.php是file声明的autoload
  21. $includeFiles = require __DIR__ . '/autoload_files.php';
  22. foreach ($includeFiles as $fileIdentifier => $file) {
  23. composerRequire32715bcfade9cdfcb6edf37194a34c36($fileIdentifier, $file);
  24. }
  25. return $loader;
  1. autoload_namespaces.php返回的是各个包里面声明的PSR-0加载规则,是一个数组。key为namespace,有可能为空字符串;value为路径的数组。
  2. $loader->set,如果$namespace/$prefix为空,直接放到$loader->fallbackDirsPsr0数组中。如果不为空,则放到$loader->prefixesPsr0[$prefix[0]][$prefix]中(这可能是为了减少PHP内部的hash表冲突,加快查找速度)。
  3. autoload_psr4.php返回的是各个包里面声明的PSR-4加载规则,是一个数组。key为namespace,有可能为空字符串;value为路径的数组。
  4. $loader->setPsr4,如果$namespace/$prefix为空,直接放到$loader->fallbackDirsPsr4数组中。如果不为空,则将$namespace/$prefix的长度放到$loader->prefixLengthsPsr4[$prefix[0]][$prefix]中,将路径放到$loader->prefixDirsPsr4[$prefix]中。
  5. autoload_classmap.php返回的是各个包里面声明的classmap加载规则,是一个数组。key为class全名,value为文件路径。(这个信息是composer扫描全部文件得到的)
  6. $loader->addClassMap,则将这些信息array_merge到$loader->classMap中。
  7. autoload_files.php返回的是各个包里面声明的file加载规则,是一个数组。key为每个文件的id/hash,value是每个文件的路径。
  8. 注意,autoload_files.php里面的文件,在getLoader中就已经被include了。

到这儿,我们的$loader已经初始化好了,而且也已经注册到SPL中了

composer加载类

我们之前是将[$loader, ‘loadClass’]注册到了SPL中,那就看看它的逻辑吧:

  1. public function loadClass($class)
  2. {
  3. if ($file = $this->findFile($class)) {
  4. includeFile($file);
  5. // 根据我们刚刚的分析,此处返回值是根本没有用
  6. return true;
  7. }
  8. }

所以看下来,重点在findFile函数里面:

  1. public function findFile($class)
  2. {
  3. // 通过classmap找这个类
  4. if (isset($this->classMap[$class])) {
  5. return $this->classMap[$class];
  6. }
  7. // 这里涉及到一个composer的性能优化:
  8. // https://getcomposer.org/doc/articles/autoloader-optimization.md#optimization-level-2-a-authoritative-class-maps
  9. if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
  10. return false;
  11. }
  12. // 这里同样也涉及到性能优化:
  13. // https://getcomposer.org/doc/articles/autoloader-optimization.md#optimization-level-2-b-apcu-cache
  14. if (null !== $this->apcuPrefix) {
  15. $file = apcu_fetch($this->apcuPrefix.$class, $hit);
  16. if ($hit) {
  17. return $file;
  18. }
  19. }
  20. // 这个函数处理了PSR-0和PSR-4的加载规则
  21. $file = $this->findFileWithExtension($class, '.php');
  22. // ……
  23. return $file;
  24. }

如果是classmap的加载规则,那就会在这儿加载成功。如果是PSR-0或者PSR-4,则需要看看findFileWithExtension的逻辑了:

  1. private function findFileWithExtension($class, $ext)
  2. {
  3. // PSR-4 lookup
  4. $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
  5. // $prefix不为空的PSR-4加载规则
  6. $first = $class[0];
  7. if (isset($this->prefixLengthsPsr4[$first])) {
  8. $subPath = $class;
  9. while (false !== $lastPos = strrpos($subPath, '\\')) {
  10. $subPath = substr($subPath, 0, $lastPos);
  11. $search = $subPath.'\\';
  12. if (isset($this->prefixDirsPsr4[$search])) {
  13. $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
  14. foreach ($this->prefixDirsPsr4[$search] as $dir) {
  15. if (file_exists($file = $dir . $pathEnd)) {
  16. return $file;
  17. }
  18. }
  19. }
  20. }
  21. }
  22. // $prefix为空的PSR-4加载规则
  23. foreach ($this->fallbackDirsPsr4 as $dir) {
  24. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
  25. return $file;
  26. }
  27. }
  28. // PSR-0 lookup
  29. if (false !== $pos = strrpos($class, '\\')) {
  30. // namespaced class name
  31. $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
  32. . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
  33. } else {
  34. // PEAR-like class name
  35. $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
  36. }
  37. // $prefix不为空的PSR-0加载规则
  38. if (isset($this->prefixesPsr0[$first])) {
  39. foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
  40. if (0 === strpos($class, $prefix)) {
  41. foreach ($dirs as $dir) {
  42. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  43. return $file;
  44. }
  45. }
  46. }
  47. }
  48. }
  49. // $prefix为空的PSR-0加载规则
  50. foreach ($this->fallbackDirsPsr0 as $dir) {
  51. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  52. return $file;
  53. }
  54. }
  55. // 从include path中找文件
  56. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
  57. return $file;
  58. }
  59. return false;
  60. }
  1. $prefix不为空的PSR-4加载规则:
    1. 比如类A\B\C,先找A\B\对应目录下面的C.php;再找A\对应目录下面的B\C.php;以此类推
  2. $prefix为空的PSR-4加载规则
    1. 如果找不到,那就在fallbackDirsPsr4下找A\B\C.php文件
  3. $prefix不为空的PSR-0加载规则
    1. PSR-0支持namespace和下划线分隔的类(PEAR-like class name);这点对一些需要向namespace迁移的旧仓库很有用
    2. 对于类A\B\C或者A_B_C,先找A\B\对应目录下面的C.php;再找A\对应目录下面的B\C.php;以此类推
  4. $prefix为空的PSR-0加载规则
    1. 如果找不到,直接在prefixesPsr0中找A\B\C.php文件
  5. 如果还没有找到,在条件允许的状态下,可以到include path中找A\B\C.php文件

这样,composer就找到了这个类对应的文件,并且include了。