PHP PSR4自动加载代码赏析

第一部分是引入自动加载配置文件

1.入口文件:autoload.php
里面没什么东西,就是导入ComposerAutoloader主题文件,一般由一个复杂的名字,不过不用担心就是机器随机生成的一个码而已,就是普通的一个类,名字比较长了。

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInitd0a5721608b46fc86f3b980fb0cea37d::getLoader();

2.自动加载主题文件:ComposerAutoloaderInitd0a5721608b46fc86f3b980fb0cea37d
getLoader(){.....}
这个就是获得自动加载的主方法,这个有点像代加工厂、里面其实只是组装了下,实际的部件在别的类(后面会提到的ClassLoader类),接下来说说getLoader方法做了哪些代加工

  • 把实际干活的小工招进厂->
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
  • 判断了下PHP版本 如果版本大于5.6 就使用闭包绑定的方式去进行绑定自动加载的配置、需要注意的是,这些内容其实都是composer dump-autoload命令生成的 所以修改了composer.json后一定要执行下该命令。下面的代码段就是给各种psr规则都设置进私有变量,闭包居然还可以这么直接搞好犀利的赶脚
return \Closure::bind(function () use ($loader) {
    $loader->prefixLengthsPsr4 = ComposerStaticInitd0a5721608b46fc86f3b980fb0cea37d::$prefixLengthsPsr4;
    $loader->prefixDirsPsr4 = ComposerStaticInitd0a5721608b46fc86f3b980fb0cea37d::$prefixDirsPsr4;
    $loader->prefixesPsr0 = ComposerStaticInitd0a5721608b46fc86f3b980fb0cea37d::$prefixesPsr0;
}, null, ClassLoader::class);
  • 如果版本小于5.6就使用原始点的方法,通过setxxx来一个个进行设置自动加载的配置,和上面实现的功能其实一样的,但是代码量就大很多了
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
    $loader->set($namespace, $path);
}

$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
    $loader->setPsr4($namespace, $path);
}

$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
    $loader->addClassMap($classMap);
}
  1. 最后把loader类注册一下
spl_autoload_register(array($this, 'loadClass'), true, $prepend);

第二部分是如何通过类名找到该文件并引入

  1. 入口方法:ClassLoader.php中的loadClass(),寻找顺序是 先classMap里找 再PSR4 PSR0 找
// class map lookup
if (isset($this->classMap[$class])) {
    return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
    return false;
}
if (null !== $this->apcuPrefix) {
    $file = apcu_fetch($this->apcuPrefix.$class, $hit);
    if ($hit) {
        return $file;
    }
}

$file = $this->findFileWithExtension($class, '.php');

// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
    $file = $this->findFileWithExtension($class, '.hh');
}

if (null !== $this->apcuPrefix) {
    apcu_add($this->apcuPrefix.$class, $file);
}

if (false === $file) {
    // Remember that this class does not exist.
    $this->missingClasses[$class] = true;
}

return $file;

posted on 2017-04-11 12:14  稀饭里的米  阅读(6873)  评论(0编辑  收藏  举报