Hiroto's diary

プログラミングとか色々

Symfonyのconsoleコンポーネントで全てのコマンド共通のオプションを設定する

PHPでコンソールアプリを作るときに使うSymfonyのconsoleコンポーネントで全てのコマンドに共通のオプションをつける方法。

Symfony\Component\Console\Applicationクラスを拡張して独自のApplicationクラスを作ってgetDefaultInputDefinitionメソッドをオーバーライドすれば共通のオプションを設定できます。

共通のオプションの値の取得はSymfony\Component\Console\Command\Commandを拡張したコマンドクラスで$input->getOption("オプション名")を叩けば取得できます。

説明は面倒なのでコードを書いておきます。

Applicationクラスのコード

<?php

namespace HirotoK\Sample\Console;

use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\InputOption;

class Application extends SymfonyApplication {

  /**
   * ここで共通のオプションを追加する。ここで設定すればコマンドクラスから$input->getOption("オプション名")で取得できる。
   *
   * @return \Symfony\Component\Console\Input\InputDefinition
   */
  protected function getDefaultInputDefinition() {
    $definition = parent::getDefaultInputDefinition();
    $definition->addOptions($this->getCommonOptions());
    return $definition;
  }

  /**
   * InputOptionのインスタンスを返す。
   *
   * @return InputOption[]
   */
  protected function getCommonOptions() {
    $options = [];
    // ここらへんで配列にInputOptionを入れていく
    $options[] = new InputOption(
        "", // オプション名
        null, // ショートカット
        InputOption::VALUE_REQUIRED, // 値の設定
        "", // 説明
        null // デフォルトの値
    );
    return $options;
  }

}

コマンドクラス

<?php

namespace HirotoK\Sample\Console\Commands;

use Symfony\Component\Console\Command\Command;

class TestCommand extends Command {

  /**
   * Configure
   *
   * @return void
   */
  protected function configure() {
    $this
      ->setName("test")
      ->setDescription("テスト用");
  }

  /**
   * Execute
   *
   * @param InputInterface $input
   * @param OutputInterface $output
   * @return void
   */
  protected function execute(InputInterface $input, OutputInterface $output) {
    var_dump($input->getOption("オプション名"));
  }

}

使う時

<?php

use HirotoK\Sample\Console\Application;
use HirotoK\Sample\Console\Commands;

$app = new Application($name, $version);
// 使うコマンドを追加
$app->add(new Commands\TestCommand);
$app->run();

© 2015 hiroxto