Symfony 2: Use console commands under a console command

Database ReIncarnation:

I wanted to create a command “database.reincarnate” which will run four other commands, for the testing purpose.

  • Database Drop (If exists)
  • Database Create
  • Update Schema
  • Load Fixtures

So, I tried to figure out how it could be done. There was on suggestion I found (2011 Blog), which didn’t work for me, with Symfony 2.7.

So, I dug a bit the documentation and here is what it worked.

class DatabaseReincarnateCommand extends Command
{

    protected function configure()
    {
        $this
            ->setName('database:reincarnate')
            ->setDescription('Database Setup (With Fixtures)');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $text = 'Dropping database ... ';
        if ($this->dropDatabase($input, $output)) {
            $text .= 'database successfully dropped ...';
        } else {
            $text .= 'database could not be dropped ...';
        }
        $output->writeln($text);

        $text = 'Creating database ... ';
        if ($this->createDatabase($input, $output)) {
            $text .= 'database successfully re-created ...';
        } else {
            $text .= 'database could not be created ...';
        }
        $output->writeln($text);

        /** more commands here **/

        $output->writeln('Database re-incarnation completed........');
        $output->writeln('.........................................');
    }

    private function dropDatabase($input, $output)
    {
        //Drop Database
        $app = $this->getApplication();
        $input = new ArrayInput(array('command'=>'doctrine:database:drop', '--force'=>true, '--if-exists' => true));
        $returnCode = $app->doRun($input, $output);

        if($returnCode == 0) {
            return true;
        } else {
            return false;
        }
    }

    private function createDatabase($input, $output)
    {
        //Create Database
        $app = $this->getApplication();
        $input = new ArrayInput(array('command'=>'doctrine:database:create'));
        $returnCode = $app->doRun($input, $output);
        if($returnCode == 0) {
            return true;
        } else {
           return false;
        }
    }
}

This entry was posted in Symfony2. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>