Calling Commands Within Commands in Symfony2

I was trying to create a command. The intent goes beyond the exercise as there are some guys already who are trying to setup an entire system from the console. But for now we will just do the command creation. The idea is to call commands within commands and for that we have the following information here which is too simple for our purposes and also here where we are told how to call commands within commands but the documentation does not elaborate too much on its uses and interesting applications.

So here I paste the code for a basic command:

<?php
namespace Cordova\CrownBundle\Command;
 
use Symfony\Bundle\FrameworkBundle\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\ArrayInput;
 
class SetupCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('crown:setup')
            ->setDescription('Crown Setup')
            ->addArgument('yesno', InputArgument::REQUIRED, 'Do you want to fire up setup? (y/n)')
            //->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters')
        ;
    }
 
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $yesno = $input->getArgument('yesno');
        if ($yesno == 'y') {
            $text = 'Running setup ... ';
            $command = $this->getApplication()->find('doctrine:fixtures:load');
            $arguments = array(
                //'--force' => true
                ''
            );
            $input = new ArrayInput($arguments);
            $returnCode = $command->run($input, $output);
            if($returnCode == 0) {
                $text .= 'fixtures successfully loaded ...';
            }
 
        } else {
            $text = 'Exiting ...';
        }
 
        /*if ($input->getOption('yell')) {
            $text = strtoupper($text);
        }*/
 
        $output->writeln($text);
    }
}

For now we just are loading the fixtures of our system. Of course this command at the moment is found redundant. However it can be well expanded into something more complex. Thanks for reading. Please consider donating.

One thought on “Calling Commands Within Commands in Symfony2

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>