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

1

5

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?

Deplete answered 18/2, 2018 at 15:27 Comment(0)
A
8

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"
Autoradiograph answered 19/2, 2018 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.