How to build a Command Line Application using PHP?

Full Article :

KernalDev - https://www.kerneldev.com/2017/12/16/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 new directory for our project and cd into it:
    $mkdir hello-world-app && cd hello-world-app
  • Require the Console Component into our project using Composer.
    $composer require symfony/console
  • 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.
    $touch HelloWorld
    $chmod +X HelloWorld
  • 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 SymfonyComponentConsoleApplication;
    use SymfonyComponentConsoleInputInputArgument;
    use SymfonyComponentConsoleInputInputInterface;
    use SymfonyComponentConsoleInputInputOption;
    use SymfonyComponentConsoleOutputOutputInterface;
    
    (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.

HelloWorld default output produces an info screen when no command is specified

The Symfony Console Component provides our app with several option’s 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 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 SymfonyComponentConsoleApplication; 
    use SymfonyComponentConsoleInputInputArgument; 
    use SymfonyComponentConsoleInputInputInterface; 
    use SymfonyComponentConsoleInputInputOption; 
    use SymfonyComponentConsoleOutputOutputInterface;
  • 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 HelloWord app in action!!:

  1. The greet  command without any arguments or options passed.                                    How to build a Command Line Application using PHP?
  2. greet with an optional name argument.                                                               How to build a Command Line Application using PHP?
  3. greet with a custom greeting.                                                                           
  4. Finally, greet a person with a custom greeting!                                                                How to build a Command Line Application using PHP?

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! and if you liked this article be sure to checkout my other tutorials in the PHP section.

The post How to build a Command Line Application using PHP? appeared first on KernelDev.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: