How to quickly build a command-line application using PHP

Source: Internet
Author: User
Tags autoload

If you are a Web development engineer, then you must use PHP many applications that have been developed Web . But do you know how to use PHP Quick Build a command line application (tool)? Below I'll show you how to PHP build a command-line application with a well-known Composer extension package,--symphony/console.

Symphony/console is a Composer management-ready PHP extension package that simplifies the process of creating a beautiful, testable command- PHP line application that provides out-of-the-box parameter specifications and option specifications (using - symbols) and other functions. So, let's start building our app together.

As a rule, we'll build a console application for "Hello World", but modify it a little bit, let it support a custom greeting (instead of Hello), and be free to greet someone (instead of world).

This Hello World application will have the following features:

    1. Provide us with a separate greet (greeting) command that we will use to interact with the application.

    2. greetYou can accept an optional parameter ( name ) to print out a person to be greeted (the default is world).

    3. greetYou can accept an option ( --say ) to change the greeting (by default, hello).

    4. If we have a given parameter or option, the program will output a Hello World message by default.

How to build a command-line application using PHP

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

    mkdir Hello-world-app && CD Hello-world-app
  • Using composer to bring console components into our project

    Composer require Symfony/console
  • Then create an entry point for your application, and the PHP extension is not required because we want to make this file an executable and specify the environment in the file itself.

    Touch Helloworldchmod +x HelloWorld
  • Add the following code to the HelloWorld file (I'll annotate each line later) and execute the application in your terminal HelloWorld .

    #!/usr/bin/env php<?phprequire __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, INPU                      toption::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 ();

Look, that's it, you have your own HelloWorld console program.

HelloWorld default output one-screen message when no command is specified

Symfony ConsoleThe component gives us an application that has several out-of-the-box options available and commands, such as help , list and--version

Explain this magical file content

OK, let's take a look at the HelloWorld code in our file.

    1. We introduced autoload.php to use the composer various features provided by the automatic loading and console components provided.

InputInterfaceAnd OutputInterface will make the application's input and output functionality easier, InputArgument and InputOption will help us to handle the options and parameters 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;
  1. symphony/consoleInstantiate a new application by name HelloWorld (v1.0.0) and register our greet commands.

    (New application (' Hello world ', ' 1.0.0 '))    ->register (' greet ')
  2. We add an optional name parameter ( addArgument() ) and provide a short description of the parameter. We then use this addOption() method to add an say option. Note that the option is always optional, but you can specify the value to be passed or just use it as a Boolean ID.

    ->addargument (' name ', inputargument::optional, ' name of the person ')->addoption (' say ', NULL, Inputoption::value _required, ' Custom greeting ')
  3. The code in the

    Setcode () method contains the main logic of our application, which prints a greeting to the terminal based on the parameters and options passed. We listen to $input objects and get passed to greet using the getargument () and getOption () helper methods Options and parameters, and then we just need to check which parameters or options are passed, and print the greeting to the console output (using the $output object) accordingly. This writeln () method can format text based on labels, such as info with different colors, error , and 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>");    }  )
  4. Finally we guide 并调用他的 the application method so that he can receive and process commands at any time greet .

    ->getapplication ()->run ();

Now let's take a look at our HelloWorld program in the example

    1. greetDo not pass any parameters and options

    1. greetThere is an optional name parameter

    1. greetsayCustomizing Greetings with options

    1. Finally, greet customize the greeting and greeting person

About the author

program developers, not confined to language and technology, is currently mainly engaged in PHP and front-end development, the use of Laravel and Vuejs. The right and enough is the never-ending pursuit.

Personal website: https://www.linganmin.cn

Note: Some of the links in this article and the image address has been replaced with a domestic address, if there are translation errors please correct me.
Happy coding!


The
original address: How to build a Command line application using PHP?

If you are a Web development engineer, then you must use PHP many applications that have been developed Web . But do you know how to use PHP Quick Build a command line application (tool)? Below I'll show you how to PHP build a command-line application with a well-known Composer extension package,--symphony/console.

Symphony/console is a Composer managed PHP extension package that simplifies the process of creating a beautiful, testable PHP command-line application that provides features such as (optional/required) parameter specifications and option specifications (using symbols) out-of-the-box - . So, let's start building our app together.

As a rule, we'll build a console application for "Hello World", but modify it a little bit, let it support a custom greeting (instead of Hello), and be free to greet someone (instead of world).

This Hello World application will have the following features:

    1. Provide us with a separate greet (greeting) command that we will use to interact with the application.

    2. greetYou can accept an optional parameter ( name ) to print out a person to be greeted (the default is world).

    3. greetYou can accept an option ( --say ) to change the greeting (by default, hello).

    4. If we have a given parameter or option, the program will output a Hello World message by default.

How to build a command-line application using PHP

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

    mkdir Hello-world-app && CD Hello-world-app
  • Using composer to bring console components into our project

    Composer require Symfony/console
  • Then create an entry point for your application, and the PHP extension is not required because we want to make this file an executable and specify the environment in the file itself.

    Touch Helloworldchmod +x HelloWorld
  • Add the following code to the HelloWorld file (I'll annotate each line later) and execute the application in your terminal HelloWorld .

    #!/usr/bin/env php<?phprequire __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, INPU                      toption::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 ();

Look, that's it, you have your own HelloWorld console program.

HelloWorld default output one-screen message when no command is specified

Symfony ConsoleThe component gives us an application that has several out-of-the-box options available and commands, such as help , list and--version

Explain this magical file content

OK, let's take a look at the HelloWorld code in our file.

    1. We introduced autoload.php to use the composer various features provided by the automatic loading and console components provided.

InputInterfaceAnd OutputInterface will make the application's input and output functionality easier, InputArgument and InputOption will help us to handle the options and parameters 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;
  1. symphony/consoleInstantiate a new application by name HelloWorld (v1.0.0) and register our greet commands.

    (New application (' Hello world ', ' 1.0.0 '))    ->register (' greet ')
  2. We add an optional name parameter ( addArgument() ) and provide a short description of the parameter. We then use this addOption() method to add an say option. Note that the option is always optional, but you can specify the value to be passed or just use it as a Boolean ID.

    ->addargument (' name ', inputargument::optional, ' name of the person ')->addoption (' say ', NULL, Inputoption::value _required, ' Custom greeting ')
  3. The code in the

    Setcode () method contains the main logic of our application, which prints a greeting to the terminal based on the parameters and options passed. We listen to $input objects and get passed to greet using the getargument () and getOption () helper methods Options and parameters, and then we just need to check which parameters or options are passed, and print the greeting to the console output (using the $output object) accordingly. This writeln () method can format text based on labels, such as info with different colors, error , and 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>");    }  )
  4. Finally we guide 并调用他的 the application method so that he can receive and process commands at any time greet .

    ->getapplication ()->run ();

Now let's take a look at our HelloWorld program in the example

    1. greetDo not pass any parameters and options

    1. greetThere is an optional name parameter

    1. greetsayCustomizing Greetings with options

    1. Finally, greet customize the greeting and greeting person

Related recommendations:

PHP command line

Detailed introduction to the Webpack command line

7 Articles about getting command-line arguments recommended

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.