yosymfony / embedded-composer
将 Composer 集成到其他应用程序中
Requires
- php: >=5.5
- composer/composer: ^1.3
This package is auto-updated.
Last update: 2024-09-13 03:54:14 UTC
README
将 Composer 集成到其他应用程序中。这个库基于 dflydev-embedded-composer。由于后者似乎已被放弃,我决定 fork 这个项目并开始自己的道路。
为什么想要集成 Composer 呢?
想象一下一个作为 phar 打包的命令行应用程序。如果希望应用程序根据所在的目录进行扩展(比如说,一个目录应使用一组插件,而另一个目录应使用完全不同的插件集),不能简单地同时在两个目录中定义 composer.json
并运行 composer install
。
为什么不行?因为应用程序附带了一组特定的依赖。Composer 无法添加更多依赖,以免引入冲突。解决方案是将 Composer 集成到应用程序中,以便 Composer 可以将已安装的应用程序的依赖与特定目录的 composer.json
中定义的依赖合并。
最终结果是满足特定目录要求的依赖集,同时考虑了控制台应用程序中已经安装的依赖。
虽然这对于分发的 phar 应用程序是必需的,但这种技术可以应用于任何需要运行时扩展的全球安装的应用程序。
使用方法
基础
以下是一个示例 bin/myapp
样式的脚本,可以使用 Composer 安装(vendor/bin/myapp
)或全局安装(/usr/local/bin/myapp
)。
myapp.php (bin)
一个共享代码块,用于从应用程序初始化嵌入式 Composer。
// assume $classLoader is somehow defined prior to this block of // code and contains the Composer class loader from the command // // see next two blocks of code use Yosymfony\EmbeddedComposer\EmbeddedComposerBuilder; $input = new ArgvInput; $projectDir = '/my-project-dir' $embeddedComposerBuilder = new EmbeddedComposerBuilder( $classLoader, $projectDir ); $embeddedComposer = $embeddedComposerBuilder ->setComposerFilename('composer.json') ->setVendorDirectory('.vendor') ->build(); $embeddedComposer->processAdditionalAutoloads(); // application is now ready to be run taking both the embedded // dependencies and directory specific dependencies into account.
myapp (bin)
示例 bin 脚本(bin/myapp
),在定位到正确的自动加载器后需要共享代码块。
#!/usr/bin/env php <?php if ( // Check where autoload would be if this is myapp included // as a dependency. (!$classLoader = @include __DIR__.'/../../../autoload.php') and // Check where autoload would be if this is a development version // of myapp. (based on actual file) (!$classLoader = @include __DIR__.'/../vendor/autoload.php') ) { die('You must set up the project dependencies, run the following commands: composer install '); } include('myapp.php');
myapp-phar-stub (bin)
示例 phar stub(bin/myapp-phar-stub
),在需要共享代码块之前可用于引导 phar 应用程序。
#!/usr/bin/env php <?php if (!$classLoader = @include __DIR__.'/../vendor/autoload.php') { die ('There is something terribly wrong with your archive. Try downloading it again?'); } include('myapp.php');
还有其他...
通过名称查找已安装的包
可以使用 findPackage
方法搜索 Composer 已安装的任何包
$package = $embeddedComposer->findPackage('acme/myapp');
创建 Composer 实例
use Composer\IO\BufferIO; // requires creating an IOInterface instance such as BufferIO $io = new BufferIO(); $composer = $embeddedComposer->createComposer($io);
创建 Composer 安装器实例
安装器实例适合处理针对外部配置的 install
和 update
操作。在解决依赖关系时,它将考虑内部(嵌入式)配置。
use Composer\IO\BufferIO; $io = new BufferIO(); $composer = $embeddedComposer->createComposer($io); $installer = $embeddedComposer->createInstaller($composer, $io);