symfonyコンソールアプリケーションで定義された2つのコマンド、clean-redis-keys
およびclean-temp-files
があります。これら2つのコマンドを実行するコマンドclean
を定義します。コマンド内から複数のSymfonyコンソールコマンドを実行する
どうすればよいですか?
symfonyコンソールアプリケーションで定義された2つのコマンド、clean-redis-keys
およびclean-temp-files
があります。これら2つのコマンドを実行するコマンドclean
を定義します。コマンド内から複数のSymfonyコンソールコマンドを実行する
どうすればよいですか?
How to Call Other Commands上のドキュメントを参照してください:
は別のものからのコマンドを呼び出すには簡単です:あなたは、コマンド名を渡すことで実行したい
use Symfony\Component\Console\Input\ArrayInput; // ... protected function execute(InputInterface $input, OutputInterface $output) { $command = $this->getApplication()->find('demo:greet'); $arguments = array( 'command' => 'demo:greet', 'name' => 'Fabien', '--yell' => true, ); $greetInput = new ArrayInput($arguments); $returnCode = $command->run($greetInput, $output); // ... }
まず、あなた
find()
コマンド。次に、コマンドに渡す引数とオプションを指定して、新しいArrayInput
を作成する必要があります。最終的に
run()
メソッドを呼び出すと、実際にコマンドが実行され、返されたコードがコマンドから返されます(コマンドのメソッドの戻り値)。
コマンドを見つけて、それらを実行、アプリケーションのインスタンスを取得します:
protected function configure()
{
$this->setName('clean');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getApplication();
$cleanRedisKeysCmd = $app->find('clean-redis-keys');
$cleanRedisKeysInput = new ArrayInput([]);
$cleanTempFilesCmd = $app->find('clean-temp-files');
$cleanTempFilesInput = new ArrayInput([]);
// Note if "subcommand" returns an exit code, run() method will return it.
$cleanRedisKeysCmd->run($cleanRedisKeysInput, $output);
$cleanTempFilesCmd->run($cleanTempFilesInput, $output);
}
コードの重複を回避するには、サブコマンドを呼び出すための汎用的なメソッドを作成することができます。このようなもの:
private function executeSubCommand(string $name, array $parameters, OutputInterface $output)
{
return $this->getApplication()
->find($name)
->run(new ArrayInput($parameters), $output);
}