How to get the file path where a class would be loaded from while using a composer autoload?

那年仲夏 提交于 2021-02-10 12:14:13

问题


A PHP 7.1 application uses composer's autoloader to find class definitions. The namespace mappings are defined in a composer.json file.

The application also uses ICU module's ResourceBundle classes to load localisable texts from *.res files. Each class with localisable texts has its own set of *.res files (one file per language). The code providing the localisation supports gets a fully qualified name of the class whose texts it should load.

I would like to have the *.res files located next to their respective class files (or in a subfolder, for example /locale/). For this I would welcome if I can somehow get the class file path without reimplementing the existing code in the composer's autoloader.

Ideally, I should be able to get the path without the need to instantiate the class and get its file location somehow.

Is this approach possible? What do you propose?


回答1:


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);

Outputs:

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


来源:https://stackoverflow.com/questions/48853306/how-to-get-the-file-path-where-a-class-would-be-loaded-from-while-using-a-compos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!