Sapnesh Naik
Senior Full Stack Software Developer
Full stack software developer with 6 years of experience building highly scalable web applications using using backend, frontend, and cloud-based technologies.

How to build a Command Line Application using PHP

December 16, 2017
How to build a Command Line Application using PHP

If you are a web developer then you most likely have used PHP in your numerous web applications but did you know that you can spin up a command-line application using PHP within no time?! Let me show you how to build a command-line application using PHP and a famous Composer package called Symphony/Console.

The Console Component (Symphony/Console) is a PHP Composer package. It eases the creation of beautiful and testable command-line applications. It provides features such as argument specification (optional/required) and option specification ( using — notation) out of the box!. So let’s get started with building our application.

We will build a customary “Hello World” console app but modify it slightly to support a custom greeting (in place of Hello) and have it optionally greet a person (instead of the world!).

The Hello World App Will:

  1. Provide us a single greet command which we will use to interact with the application.
  2. greet can accept an optional argument (name) to print out a greeting to the person (default is World).
  3. greet can accept an option (–say) to change the greeting message (default is Hello).
  4. If no arguments or options are specified give us a default Hello world message.

How to Build a Command-Line Application Using PHP:

  • Create a new directory for our project and cd into it: `

  • Require the Console Component into our project using Composer. `

  • Now create an entry point to your application. A PHP extension is not necessary as we are going to make this file executable and specify the environment in the file itself. `

  • Add the code below to HelloWorld file ( I will explain what each line does in a moment!) and execute the HelloWorld app in your terminal.

    #!/usr/bin/env php
    <?php
    require __DIR__.'/vendor/autoload.php';
    
    use Symfony\Component\Console\Application;
    use Symfony\Component\Console\Input\InputArgument;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Input\InputOption;
    use Symfony\Component\Console\Output\OutputInterface;
    
    (new Application('Hello World', '1.0.0'))
          ->register('greet')
    
          ->addArgument('name', InputArgument::OPTIONAL, 'Name of the person')
    
          ->addOption('say', null, InputOption::VALUE_REQUIRED, 'Custom greeting')
    
          ->setCode(function (InputInterface $input, OutputInterface $output) {
    
            $name = $input->getArgument('name');
            $greeting = $input->getOption('say');
    
            if (!empty($name) && !empty($greeting)) {
                return $output->writeln("<info>$greeting $name!</info>");
            } else if (!empty($name)) {
                return $output->writeln("<info>Hello $name!</info>");
            } else if (!empty($greeting)) {
                return $output->writeln("<info>$greeting World!</info>");
            } else {
                return $output->writeln("<info>Hello World!</info>");
            }
    })
    ->getApplication()
    ->run();

    Voilà! and that is it. You have your HelloWorld Console application.

    Build a command line application using PHP

    The Symfony Console Component provides our app with several options and commands such as help, list and –version out of the box!

Explain This Sorcery Human!

Okay, Let’s take a look at the code in our HelloWorld file.

  • We require the autoload.php provided by the composer for autoloading and also the various features provided by the Console component. InputInterface and OutputInterface will facilitate the input and output functionalities of the application and similarly InputArgument and InputOption will help us process the options and arguments passed to our HelloWorld application.

    require __DIR__.'/vendor/autoload.php';
    
    use Symfony\Component\Console\Application;
    use Symfony\Component\Console\Input\InputArgument;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Input\InputOption;
    use Symfony\Component\Console\Output\OutputInterface;
  • Instantiate a new symphony/console application by the name HelloWorld (v1.0.0) and register our greet command.

    (new Application('Hello World', '1.0.0'))->register('greet')
  • We add an optional name argument (addArgument()) and also provide a short description of the argument. We then add an option say using the addOption() method. Note that options are always optional but you can either specify the options to be passed with a value or they can also be used just as a flag which will specify a boolean.

    ->addArgument('name', InputArgument::OPTIONAL, 'Name of the person')
    ->addOption('say', null, InputOption::VALUE_REQUIRED, 'Custom greeting')
  • The code in setCode() method will contain the main logic of our app. It will print out a greeting to the terminal depending upon the argument and options passed also notice that we get the options and arguments passed to the greet command using the getArgument() and getOption() helper methods on the $input object. We then simply check which arguments or options were passed and print a greeting to the console output (using the $output object) accordingly. The writeln method can format the output to different colors based on tags such as info, errorand `warning.

    ->setCode(function (InputInterface $input, OutputInterface $output) {
        $name = $input->getArgument('name');
        $greeting = $input->getOption('say');
    
        if (!empty($name) && !empty($greeting)) {
            return $output->writeln("<info>$greeting $name!</info>");
        } else if (!empty($name)) {
            return $output->writeln("<info>Hello $name!</info>");
        } else if (!empty($greeting)) {
            return $output->writeln("<info>$greeting World!</info>");
        } else {
            return $output->writeln("<info>Hello World!</info>");
        }
    })
  • We finally bootstrap the application using getApplication() and call the run() method on it so that it will be ready to accept and process out greet command.

     ->getApplication()->run();

Now Let’s See Our Hello World App in Action!

  1. The greet command without any arguments or options passed.

    The greet command

  2. greet with an optional name argument.

    Greet command with optional name argument

  3. greet with a custom greeting.

    Greet with a custom greeting

  4. Finally, greet a person with a custom greeting!

    Greet a person with a custom greeting

So that’s it! You have your command line application in a jiffy! You can find the complete source code in my GitHub repo.

So what do you think? Share your thoughts in the comment section below!