Symfonyのカスタムコマンド

Pocket

Symfonyはコマンドが充実しています。また自作のコマンドをシンプルに作成できます。
自作コマンドとしてテーブル一覧を表示するサンプルを掲載しています。

Symfonyでは規約として、バンドルのCommandディレクトリにある、名前にCommandというサフィックスの付いたクラスが、コマンドとして自動的に登録されます。

基本からしっかり学ぶ Symfony2入門 (p187)

<?php
namespace AppBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TableListCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('foo:table:list')
            ->setDefinition(
                [
                    new InputArgument('name', InputArgument::OPTIONAL, 'table name'),
                ]
            )->setDescription('Show table list.');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();
        $sm        = $container->get('database_connection')->getSchemaManager();
        $tables    = $sm->listTables();

        $name = $input->getArgument('name');
        if (!empty($name)) {
            foreach ($tables as $table) {
                if ($table->getName() === $name) {
                    $output->writeln('yes');

                    return;
                }
            }
            $output->writeln('no');

            return;
        }

        // Show tables when argument is none.
        $list = '';
        foreach ($tables as $table) {
            $list .= $table->getName().PHP_EOL;
        }
        $output->writeln($list);
    }
}
$ app/console foo.table.list
// 引数なしのときはテーブル一覧を表示
$ app/console foo.table.list hoge
// hogeテーブルがあればyes, なければno

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。