ECCUBE4

【EC-CUBE4】 Command(コマンド)について

こんにちは、Junです。

この記事では、EC-CUBE4でコマンドの基本について解説します。

コマンドの作成

コマンドは、「Symfony\Component\Console\Command\Command」クラスを継承して作成します。

<?php

namespace Customize\Command;

use Symfony\Component\Console\Command\Command;

class ProductStockCheckCommand extends Command
{
}

コマンド名

コマンド名は、「protected static」の変数「$defaultName」で設定します。

protected static $defaultName = 'eccube:product-stock:check';

コマンド時のメッセージ

コマンド時のメッセージは主に、5で「text」,「success」,「error」,「warning」,「note」,「caution」があります。基本的には、successとerrorが表示できれば良いかと思います。

処理に応じて、記載するとわかりやすくなります。

表示は次のような画像になります。

protected function execute(InputInterface $input, OutputInterface $output)
{
        $io = new SymfonyStyle($input, $output);

        $io->text('text');
        $io->success('success');
        $io->error('error');
        $io->warning('warning');
        $io->note('note');
        $io->caution('caution');
}

コマンド実行時の処理

コマンド実行時の処理は、「execute」メソッドをオーバーライドすることで、実現できます。

protected function execute(InputInterface $input, OutputInterface $output)
{
  コマンド実行時処理を記載する。
  ・・・・
}      

オプション入力

コマンド実行時に、インプットオプションを追加することも可能です。

「configure」メソッドをオーバーライドして、設定します。

「execute」メソッドの中で、オプションの値を取得することで、処理の中で利用することができます。

    protected function configure()
    {
        $this->addOption('option',null,InputOption::VALUE_OPTIONAL);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $option = $input->getOption('option');
    }

以下の例では、「option」というオプションにtestという値をインプットしました。

php bin/console command:command:command --option=test

以上です。