In example below, we're going to create a console command as a standalone application. You can also include this application in another application by requiring "inanzzz/hello-console-command": "dev-master" in composer.json file.


Project structure


my-test-app
bin
console
src
Command
HelloCommand.php
composer.json

Composer.json file


After creating the composer.json in project root, you need to run composer install command.


{
"name": "inanzzz/hello-console-command",
"description": "Say hello package.",
"type": "library",
"version": "1.0.0",
"autoload": {
"psr-0": {
"Command": "src/"
}
},
"require": {
"symfony/console": "2.*"
},
"minimum-stability": "stable",
"bin": [
"bin/console"
]
}

Console file


Create bin/console file and grant executable permissions to it with chmod +x bin/console command.


#!/usr/bin/env php
<?php
set_time_limit(0);

(@include_once __DIR__ . '/../vendor/autoload.php') || @include_once __DIR__ . '/../../../autoload.php';

use Command\HelloCommand;
use Symfony\Component\Console\Application;

$app = new Application('My CLI Application', '1.0.0');
$app->add(new HelloCommand());
$app->run();

HelloCommand.php file


# src/Command/HelloCommand.php
<?php

namespace Command;

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

class HelloCommand extends Command
{
protected function configure()
{
$this
->setName('say:hello')
->setDescription('Say hello to someone')
->addArgument(
'name',
InputArgument::OPTIONAL,
'Who do you want to say hello?'
);
}

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

$output->writeln($hello);
}
}

Test


my-test-app$ bin/console say:hello inanzzz
Hello inanzzz