如何在使用作曲家自动加载时获取 class 从中加载的文件路径?
How to get the file path where a class would be loaded from while using a composer autoload?
A PHP 7.1 应用程序使用 composer 的自动加载器来查找 class 定义。命名空间映射在 composer.json
文件中定义。
该应用程序还使用 ICU 模块的 ResourceBundle
classes 从 *.res
文件加载可本地化的文本。每个带有可本地化文本的 class 都有自己的一组 *.res
文件(每种语言一个文件)。提供本地化支持的代码获取 class 应加载其文本的完全限定名称。
我希望 *.res
文件位于它们各自的 class 文件旁边(或在子文件夹中,例如 /locale/
)。为此,如果我能以某种方式获得 class 文件路径而无需在作曲家的自动加载器中重新实现现有代码,我会很高兴。
理想情况下,我应该能够在不需要实例化 class 的情况下获取路径并以某种方式获取其文件位置。
这种方法可行吗?你有什么建议?
是的,有可能,实际上需要 'vendor/autoload.php'
returns 自动加载器实例:
/* @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"
A PHP 7.1 应用程序使用 composer 的自动加载器来查找 class 定义。命名空间映射在 composer.json
文件中定义。
该应用程序还使用 ICU 模块的 ResourceBundle
classes 从 *.res
文件加载可本地化的文本。每个带有可本地化文本的 class 都有自己的一组 *.res
文件(每种语言一个文件)。提供本地化支持的代码获取 class 应加载其文本的完全限定名称。
我希望 *.res
文件位于它们各自的 class 文件旁边(或在子文件夹中,例如 /locale/
)。为此,如果我能以某种方式获得 class 文件路径而无需在作曲家的自动加载器中重新实现现有代码,我会很高兴。
理想情况下,我应该能够在不需要实例化 class 的情况下获取路径并以某种方式获取其文件位置。
这种方法可行吗?你有什么建议?
是的,有可能,实际上需要 'vendor/autoload.php'
returns 自动加载器实例:
/* @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"