johannesdold
9/20/2017 - 10:03 AM

Template for Console Command

Template for Console Command for Pimcore with iteration over objects and progress bar

Use command in console

php www/pimcore/cli/console.php mynamespace:my-template-command

Comments

  • php must be an alias for the php cli executable

  • command called from git root of project

  • Class must lie under

    www/website/lib/Website/Console/Command/MyTemplateCommand.php
    

    that pimcore automatically autoloads the class

<?php
namespace Website\Console\Command;

use Pimcore\Console\AbstractCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\ProgressBar;

class MyTemplateCommand extends AbstractCommand
{
    protected function configure()
    {
        $this
            ->setName('mynamespace:my-template-command')
            ->setDescription('template command')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // fill objects with listing e.g.
        $objects = [];

        $progress = new ProgressBar($this->output, count($objects));
        $progress->setFormat('[%bar%] - (%current%/%max%) %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');

        $this->output->writeln('Start iteration:');
        $progress->start();

        if (!empty($objects)) {
            foreach ($objects as $object) {
                // do something
                $progress->advance();
            }
        }

        $progress->finish();
    }

    protected function verboseMessage($m)
    {
        if ($this->output->isVerbose()) {
            $this->output->writeln($m);
        }
    }
}