我尝试通过使用PHP要求新的composer程序包,在Google上进行大量研究后,我发现Composer提供了官方选项\Composer\Installer,并开始创建一个小型原型。
$installer->run()
给我0
表示成功,但是结果却不是我所期望的,我认为我做错了。
<?php
//...
$installer = Installer::create($io, $composer)
->setPreferDist()
->setSkipSuggest()
->setUpdate()
->setDumpAutoloader()
->setRunScripts(false)
->setOptimizeAutoloader(true);
try {
$status = $installer->run();
} catch (\Throwable $exception) {
$status = 1;
}
//...
这是我完整的PHP脚本:
<?php
namespace mlaxwong\composer;
use Composer\Factory;
use Composer\Installer;
use Composer\Json\JsonFile;
use Composer\Json\JsonManipulator;
use Composer\IO\IOInterface;
use Composer\IO\NullIO;
use Composer\Package\Locker;
class Composer
{
public function install(array $requirements, IOInterface $io = null)
{
// try everything I can ..... ignore this 4 lines
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('memory_limit', '-1');
if ($io === null) $io = new NullIO;
$jsonPath = dirname(__DIR__) . '/composer.json';
$wd = dirname($jsonPath);
// chdir($wd);
$backup = file_get_contents($jsonPath);
$config = $this->composerConfig($io, $jsonPath, true);
$composer = Factory::create($io, $config);
$lockFile = pathinfo($jsonPath, PATHINFO_EXTENSION) === 'json'
? substr($jsonPath, 0, -4) . 'lock'
: $jsonPath . '.lock';
$rm = $composer->getRepositoryManager();
$im = $composer->getInstallationManager();
$locker = new Locker($io, new JsonFile($lockFile, null, $io), $rm, $im, file_get_contents($jsonPath));
$composer->setLocker($locker);
$success = true;
$manipulator = new JsonManipulator(file_get_contents($jsonPath));
$requireKey = 'require';
$removeKey = 'require-dev';
foreach ($requirements as $package => $constraint)
{
if (
!$manipulator->addLink($requireKey, $package, $constraint, true) ||
!$manipulator->removeSubNode($removeKey, $package)
) {
$success = false;
break;
}
}
if ($success) file_put_contents($jsonPath, $manipulator->getContents());
$installer = Installer::create($io, $composer)
->setPreferDist()
->setSkipSuggest()
->setUpdate()
->setDumpAutoloader()
->setRunScripts(false)
->setOptimizeAutoloader(true);
try {
$status = $installer->run();
} catch (\Throwable $exception) {
$status = 1;
}
// chdir($wd);
if ($status !== 0)
{
file_put_contents($jsonPath, $backup);
throw $exception ?? new \Exception('An error occurred');
}
}
protected function composerConfig(IOInterface $io, string $jsonPath, bool $prepForUpdate = true): array
{
$file = new JsonFile($jsonPath, null, $io);
$config = $file->read();
return $config;
}
}
并通过以下测试:
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use mlaxwong\composer\Composer;
$composer = new Composer;
$composer->install(['yiisoft/yii-core' => "*"]);
使用示例代码,我能够:
我停留了这两天……我想我已经快到了,但是Google上的文档确实很少。
我真的需要您的帮助,对不起我的英语,并感谢您抽出宝贵时间阅读我的问题。
总结我的目标:
$composer->install(["package-name", "version"]);
安装新的作曲家软件包再次感谢:)