Symfony2にいくつかのコンソールコマンドがあり、いくつかのパラメーターを使用して別のコマンドから1つのコマンドを実行する必要があります。
2番目のコマンドを正常に実行した後、表示出力ではなく、結果(たとえば、配列として)を取得する必要があります。
どうやってやるの?
ここでは、コマンド内に基本的なコマンドを含めることができます。2番目のコマンドからの出力はjsonにすることができ、配列を取得するには出力jsonをデコードする必要があります。
$command = $this->getApplication()->find('doctrine:fixtures:load');
$arguments = array(
//'--force' => true
''
);
$input = new ArrayInput($arguments);
$returnCode = $command->run($input, $output);
if($returnCode != 0) {
$text .= 'fixtures successfully loaded ...';
$output = json_decode(rtrim($output));
}
引数配列でコマンドを渡す必要があります。また、doctrine:fixtures:loadの確認ダイアログを回避するには、-forceではなく--appendを渡す必要があります。
$arguments = array(
'command' => 'doctrine:fixtures:load',
//'--append' => true
''
);
または、「引数が足りません」というエラーメッセージが表示されて失敗します。</ p>
と呼ばれる新しいOutputクラス(v2.4.0以降)がありBufferedOutput
ます。
fetch
これは非常に単純なクラスであり、メソッドが呼び出されたときにバッファリングされた出力を返し、クリアします。
$output = new BufferedOutput();
$input = new ArrayInput($arguments);
$code = $command->run($input, $output);
if($code == 0) {
$outputText = $output->fetch();
echo $outputText;
}
私は次のことをしました
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;
$tmpFile = tmpfile();
$output = new StreamOutput($tmpFile);
$input = new ArrayInput(array(
'parameter' => 'value',
));
$command = . . .
$command->run($input, $output);
fseek($tmpFile, 0);
$output = fread($tmpFile, 1024);
fclose($tmpFile);
echo $output;
できます!
私はそれが古い投稿であることを理解しており、上記の答えは少し掘り下げることで問題を解決します。Symfony2.7では、それを機能させるのに少し問題があったので、上記の提案で少し掘り下げて、ここに完全な答えをまとめました。それが誰かのために役立つことを願っています。
Onemaの回答の更新として、Symfony 3.4.x(Drupal 8で使用)では、
setAutoExit(false)
、int(0)
。Drupal8.8プロジェクトのphpでcomposerコマンドをスクリプト化するために使用している更新された例を次に示します。これにより、すべてのコンポーザーパッケージのリストがjsonとして取得され、それがphpオブジェクトにデコードされます。
<?php
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Composer\Console\Application;
$input = new ArrayInput([
'command' => 'show',
'--format'=>'json',
]);
$output = new BufferedOutput();
$application = new Application();
// required to use BufferedOutput()
$application->setAutoExit(false);
// composer package list, formatted as json, will be barfed into $output
$status = $application->run($input, $output);
if($status === 0) {
// grab the output from the $output buffer
$json = $output->fetch();
// decode the json string into an object
$list = json_decode($json);
// Profit!
print_r($list);
}
?>
出力は次のようになります。
stdClass Object
(
[installed] => Array
(
... omitted ...
[91] => stdClass Object
(
[name] => drupal/core
[version] => 8.9.12
[description] => Drupal is an open source content management platform powering millions of websites and applications.
)
... omitted ...
)
)