Symfony2 Console Component

Andy Truong 9th March 2015

Twitter: thehongtt

Why?

PHP components are awesome! But how can I run it without WEB?

Why?

  • Get command arguments/options
  • Print status/error/table
  • Run sub process?
  • Get user's in time input
  • Confirmation

Why?

I want a good structure to organise my CLI application

  • Easy maintenance
  • Reuse
  • Testable

How?

Define composer.json

{
  "require": {
    "symfony/console": "2.6.4"
  },
  "autoload": {
    "psr-4": {
      "AndyTruong\\ConsoleTalk\\": "src"
    }
  }
}

Front controller

<?php

use AndyTruong\ConsoleTalk\HelloCmd;
use AndyTruong\ConsoleTalk\PlayroundCmd;
use Symfony\Component\Console\Application;

require_once __DIR__ . '/vendor/autoload.php';

$app = new Application('AT console talk', '0.1.0');
$app->add(new HelloCmd());
$app->add(new PlayroundCmd());
$app->run();

Command: Metadata

<?php

namespace AndyTruong\ConsoleTalk;

use Symfony\Component\Console\Command\Command;

class HelloCmd extends Command
{
    public function configure()
    {
        $this
            ->setName('at:demo:hello')
            ->setDescription('Just say Hello to all the world!')
            ->addArgument('name', InputArgument::OPTIONAL)
            ->addOption('language', 
                $shortcut = null, 
                InputOption::VALUE_OPTIONAL, 
                'Language to speak.', 'en'
            );
    }
}

Command: Logic

<?php

namespace AndyTruong\ConsoleTalk;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class HelloCmd extends Symfony\Component\Console\Command\Command
{

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name') ?: 'world!';

        switch ($input->getOption('language')) {
            case 'vi':
                $output->writeln("Chào {$name}!");
                break;
            case 'en':
            default:
                $output->writeln("Hello {$name}!");
                break;
        }
    }
}

Command: Action

php cli at:demo:hello
!! "Andy"
!! --language=vi

Symfony2 Console component

By Andy Truong

Symfony2 Console component

  • 994