【问题标题】:How to get the file path where a class would be loaded from while using a composer autoload?如何在使用作曲家自动加载时获取加载类的文件路径?
【发布时间】:2018-02-18 15:27:52
【问题描述】:

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

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

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

理想情况下,我应该能够获取路径,而无需实例化类并以某种方式获取其文件位置。

这种方法可行吗?你有什么建议?

【问题讨论】:

    标签: php composer-php autoload


    【解决方案1】:

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

    /* @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"
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 2014-08-15
      • 2018-08-26
      • 2021-06-27
      • 2017-01-14
      • 2018-02-27
      • 2013-02-02
      • 2021-12-18
      相关资源
      最近更新 更多