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;

转载于:https://www.cnblogs.com/wangmy/p/6692970.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值