Symfony console – step-by-step

Symfony console - command line

Not only www, but Symfony also have a huge library of features to command line, including style, formater, progress bars, and so on.

If your time is expensive or you’re simply lazy, then you may use this step-by-step instruction to create a new command in the Symfony framework.

1. Install composer https://getcomposer.org/

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
sudo mv composer.phar /usr/local/bin/composer

2. Install Symfony

wget https://get.symfony.com/cli/installer -O - | bash
sudo mv /home/user-name/.symfony/bin/symfony /usr/local/bin/symfony

3. Create project

symfony check:requirements
symfony new command-test

4. Install symfony maker to symfony

composer require symfony/maker-bundle --dev

5. Create command – our example send-email

php bin/console make:command your

Output:

created: src/Command/YourCommand.php
Success!

6. Imlement it

Dont forget to implement

<?php

namespace App\Command;

use Symfony\Component\Console\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\Style\SymfonyStyle;

class YourCommand extends Command
{
    protected static $defaultName = 'your';

    protected function configure()
    {
        $this
            ->setDescription('Add a short description for your command')
            ->addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
            ->addOption('option1', null, InputOption::VALUE_NONE, 'Option description')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $arg1 = $input->getArgument('arg1');

        if ($arg1) {
            $io->note(sprintf('You passed an argument: %s', $arg1));
        }

        if ($input->getOption('option1')) {
            // ...
        }

        $io->success('You have a new command! Now make it your own! Pass --help to see your options.');

        return Command::SUCCESS;
    }
}

7. Run it!

php bin/console your --help
php bin/console your

Leave a Reply

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