且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在使用作曲家自动加载时获取从中加载类的文件路径?

更新时间:2023-11-17 10:16:10

是的,有可能需要'vendor/autoload.php'实际上返回一个自动加载器实例:

Yes, it is possible, require 'vendor/autoload.php' actually returns an autoloader instance:

/* @var $loader \Composer\Autoload\ClassLoader */
$loader = require 'vendor/autoload.php';

$class = \Monolog\Logger::class;

$loggerPath = $loader->findFile($class);
if (false === $loggerPath) {
    throw new \RuntimeException("Cannot find file for class '$class'");
}
$realLoggerPath = realpath($loggerPath);
if (false === $realLoggerPath) {
    throw new \RuntimeException("File '$loggerPath' found for class '$class' does not exists");
}

var_dump($realLoggerPath);

输出:

string(64) "/home/user/src/app/vendor/monolog/monolog/src/Monolog/Logger.php"