我正在尝试从 Composer 包中查找应用程序的基目录。是否有 Composer API 或正确的方法来完成此任务。
澄清一下,如果我的软件包安装看起来像这样,并且我在这里有文件(使用 psr-4):
/home/project/vendor/Acme/my-package/src/
如何动态找到/home/project?
更新信息:
我正在尝试从根目录加载 .env 文件,该文件包含通过包内的 Dotenv 包的 API URL 端点。
这应该做:
<?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) 一样,避免全局安装,但仍加载引导文件。 Composer 允许 bin 文件安装在根目录https://getcomposer.org/doc/articles/vendor-binaries.md,但允许用户将 phar 文件放置在他们认为合适的任何地方是一个优点。
人们可能会争论控制反转,但在我看来,简单性有时应该发挥作用。
啊..我想我已经明白了..
因为我在index.php中使用了
include_once './vendor/autoload.php';
,所以我可以使用包中的getcwd()
基于@Sven 的输入,最好、最干净的解决方案是收集类初始化的输入并将配置保留在包之外。
尝试
saboohy/basepath
套餐。提供项目目录。
试试这个:
$basePath = explode('/vendor', __FILE__)[0];