故障现象与初步排查
故障现象
团队采用PHP语言结合Laravel框架进行开发。近期线上环境频繁报错,经排查发现根源在于Composer安装的第三方库提示类未找到(class not found)。此前在Lumen框架下曾遭遇类似状况,其成因多为composer.json文件中“autoload”节点下的“psr-4”配置格式存在瑕疵。针对此类问题,可通过执行命令`composer dump-autoload -o`进行修复。
尽管已明确常规解决方案,但一个疑点尚待厘清:该第三方包长期稳定运行,为何近期突然触发报错?下文将展开对这一异常现象的深度溯源。
应对策略
若已确认第三方包安装无误且代码中正确使用了use引用,建议优先尝试执行`composer dump-autoload -o`命令以重新生成优化后的自动加载文件。
处理结论
鉴于篇幅限制,先同步最终排查结果:具体根因尚未精准定位。目前推测可能与发布服务器的环境配置有关,但由于服务器承载多项监控服务,出于稳定性考虑禁止直接测试,故导致环境差异的具体配置项仍未查明。
下文将详细记录问题的分析与解决全过程。
1. 查看laravel autoload
2. 查看composer源码;
3. 重新编译composer打印日志;
4. 分析composer install过程;
5. 查看php artisan optimize源码
对技术细节感兴趣的读者可继续阅读后续内容。
问题分析及解决过程
1. 探究class not found的根本原因
推导思路
既然系统报出class not found,说明Composer包本身已安装成功。因此,问题焦点应锁定在自动加载(autoload)环节的执行逻辑上。
源码追踪
首先从自动加载的入口文件`public/index.php`开始分析。
require __DIR__.'/../bootstrap/autoload.php';
随后跟进进入`bootstrap/autoload.php`文件。
require __DIR__.'/../vendor/autoload.php';
接着查看`vendor/autoload.php`的内容。
// require 自动加载类
require_once __DIR__ . '/composer/autoload_real.php';
// 真正返回文件列表的操作
return ComposerAutoloaderInit3f39d071b2e74e04102a9c9b6f221123::getLoader();
重点关注其中的`getLoader()`方法实现。
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
// 注册自动加载方法,用来后面初始化ClassLoader类
spl_autoload_register(array('ComposerAutoloaderInit3f39d071b2e74e04102a9c9b6f221123', 'loadClassLoader'), true, true);
// 初始化ClassLoarder
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit3f39d071b2e74e04102a9c9b6f221123', 'loadClassLoader'));
// 这里zend_loader_file_encoded查了一下,解释为:
// Returns TRUE if the current file was encoded with Zend Guard or FALSE otherwise. If FALSE, consider disabling the Guard Loader
// 又查了一下Zend Guard,貌似是php代码加密并提高执行效率的,提高有限,比较鸡肋
// 打印了一下,发现不存在这个方法,即!function_exists('zend_loader_file_encoded')为true
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
// 程序在这里执行
// 引用ComposerStaticInit类
require_once __DIR__ . '/autoload_static.php';
// 调用ComposerStaticInit类中的getInitializer方法
// 主要作用是使用ComposerStaticInit类中的值初始化上面创建的ComposerAutoloader对象中的prefixLengthsPsr4、prefixDirsPsr4、prefixesPsr0、classMap等值
call_user_func(\Composer\Autoload\ComposerStaticInit3f39d071b2e74e04102a9c9b6f221123::getInitializer($loader));
} else {
$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);
}
}
// 重点在这个方法
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit3f39d071b2e74e04102a9c9b6f221123::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire3f39d071b2e74e04102a9c9b6f221123($fileIdentifier, $file);
}
return $loader;
}
观察`ClassLoader`类的`register`方法注册过程。
public function register($prepend = false)
{
// 调用ClassLoader类的loadClass方法
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
深入`ClassLoader`类的`loadClass`核心逻辑。
public function loadClass($class)
{
// 查找文件,如果查找到文件,则加载文件
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
分析`ClassLoader`类的`findFile`文件查找方法。
public function findFile($class)
{
// class map lookup
// class map加载方式,我的理解:是通过将类与对应路径生成一个对应表
// 该方式优点:加载速度快,相当于查询字典;
// 缺点:无法实现自动加载,添加新类后,需要对应维护class map
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
// $classMapAuthoritative默认值为false,流程到目前,没有设置过该值
// $missingClasses通过查看该方法最后几行,发现作用是记录自动加载过程中不存在的文件
// 所以这里第一次加载会返回false
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
// APCu 是老牌 PHP 字节码和对象缓存,缓存器 APC 的分支(PS:我也是查的,不懂呀~大家感兴趣可以自己深研究)
// 经测试,$this->apcuPrefix=null
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;
}
进一步研究`ClassLoader`类中的`findFileWithExtension`扩展名匹配方法。
private function findFileWithExtension($class, $ext)
{
// 终于看到加载psr-4了
// PSR-4 lookup
// 对路径中的\转换为文件系统中对应路径分隔符并+后缀,
// 比如wan\test类,最后处理为wan/test.php(linux下)
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
// 获得类名中第一个字母,主要用于在ClassLoader中prefixLengthsPsr4快速检索包,并找到对应包前缀长度,后面截取时使用
// 对比autoload_static.php中的$prefixLengthsPsr4即可明白作用
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
// 从右往左一层层循环类名中的路径
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath.'\\';
// 找到对应composer包前缀后,取出对应路径,将包前缀截取后,替换成对应的目录路径,即为class所对应文件
if (isset($this->prefixDirsPsr4[$search])) {
foreach ($this->prefixDirsPsr4[$search] as $dir) {
$length = $this->prefixLengthsPsr4[$first][$search];
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
return $file;
}
}
}
}
}
// 到这里psr-4文件就加载完了,后面是psr-0等其他文件加载,这里就不分析了。
// 这里分析一下为什么是第三方包psr-4格式错误
// 比如包名为wan/lib,即composer安装命令对应composer require wan/lib
// 第三方包中autoload psr-4配置为 "psr-4" : { "wan\\" : "src" }
// (**警告:上面是错误配置,为了举例说明;正确应该是"psr-4" : { "wan\\lib\\" : "src" })
// 最终生成的$prefixLengthsPsr4为{'w' =>array ('wan\\' => 5,),}
// 生成$prefixDirsPsr4为'wan\\' => array (0 => __DIR__ . '/..' . '/wan/lib/src',),
// 对应上面代码,在最后$file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length)
// $file拼接出来的路径是vendor/wan/lib/src/lib/$className.php,导致最后无法拼接出正确路径
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
阶段总结
由于源码追踪链条较长,致使文章篇幅增加,因此决定将此部分内容拆分为系列文章进行阐述。
至此,通过对Laravel框架autoload机制源码的全面梳理,掌握了Composer包中psr-4及classmap信息的正确配置方式。
后续章节将通过分析Composer源码及`php artisan`命令源码,进一步解释为何本地开发及测试环境未复现此class not found问题。
以上即为Laravel第三方包class not found错误的解决方法分享,旨在提供参考并感谢支持。