如何在使用作曲家自动加载时获取从中加载类的文件路径? [英] How to get the file path where a class would be loaded from while using a composer autoload?

查看:65
本文介绍了如何在使用作曲家自动加载时获取从中加载类的文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 7.1应用程序使用作曲家的自动加载器来查找类定义.名称空间映射在 composer.json 文件中定义.

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

该应用程序还使用ICU模块的 ResourceBundle 类从 *.res 文件加载可本地化的文本.每个具有可本地化文本的类都有其自己的 *.res 文件集(每种语言一个文件).提供本地化支持的代码获得了应该加载其文本的类的完全限定名称.

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.

我想让 *.res 文件位于它们各自的类文件旁边(或在子文件夹中,例如/locale/).为此,如果我能以某种方式获得类文件路径而无需重新实现作曲家的自动加载器中的现有代码,我将非常欢迎.

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?

推荐答案

是的,有可能需要'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"

这篇关于如何在使用作曲家自动加载时获取从中加载类的文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆