如何从composer包中查找安装vendor的基本目录


How to find the base directory where vendor is installed from a composer package

我正试图从composer包中找到应用程序的基本目录。是否有一个作曲家API或正确的方法来实现这一点。

为了澄清,如果我的软件包安装看起来像这样,并且我在这里有文件(使用psr-4):

/home/project/vendor/Acme/my-package/src/

如何动态查找/home/project?

更新信息:

我正在尝试从根加载一个.env文件,该文件包含一个API URL端点,通过包中的Dotenv包。

这应该做:

<?php
$root = null;
// Set the current directory.
// Make sure you set this up so
// that you get out of your own root.
// Assuming this php file is at the root
// of this composer package, this should suffice.
$directory = dirname(__FILE__);
// Go up until you find a composer.json file
// which should exist in the ancestors
// because its a composer package.
do {
    $directory = dirname($directory);
    $composer = $directory . '/composer.json';
    if(file_exists($composer)) $root = $directory;
} while(is_null($root) && $directory != '/');
// We either are at the root or we got lost.
// i.e. a composer.json was nowhere to be found.
if(!is_null($root))
{
    // Yay! we are at the root.
    // and $root contains the path.
    // Do whatever you seem fit!
    bootstrapOrSomething();
}
else
{
    // Oh no! Can we default to something?
    // Or just bail out?
    throw new Exception('Oops, did you require this package via composer?');
}

@sven在某些情况下,这种策略可能会有所帮助。就像任何项目的通用控制台应用程序(phar)一样,避免全局安装,但仍然加载bootsrap文件。Composer允许在根目录下安装bin文件https://getcomposer.org/doc/articles/vendor-binaries.md,但允许用户将phar文件放在他们认为合适的地方是一个优势。

人们可能会争论控制权的倒置,但有时简单性应该发挥作用。

啊。。我想我已经想通了。。

由于我在index.php中使用了include_once './vendor/autoload.php';,我只能使用包中的getcwd()

基于@Sven的输入,最好和最干净的解决方案是收集类初始化的输入,并将配置排除在包之外。

尝试saboohy/basepath包。给出项目的目录。