How to quickly build command line applications using PHP

小云云
Release: 2023-03-18 06:00:01
Original
1869 people have browsed it

If you are a Web development engineer, then you must have developed many Web applications using PHP . But do you know how to quickly build a command line application (tool) using PHP? Below I will show you how to use PHP and a famous ComposerExtension package--Symphony/Console builds a command line application.

Symphony/Console is a PHP extension package managed with Composer that simplifies creating a beautiful, testable PHP command It provides out-of-the-box functions such as (optional/required) parameter specification and option specification (using - symbols). So, let's start building our application together.

As usual, we will build a "Hello World" console application, but modify it slightly so that it supports a custom greeting (instead of Hello) and can greet someone at will. (instead of world).

This Hello World application will have the following functions:

  1. Provides us with a separate greet (greeting) command, which we will use It comes to interact with the application.

  2. greet can accept an optional parameter (name) to print out a person being greeted (default is World).

  3. greetCan accept an option (--say) to change the greeting (default is Hello).

  4. If we give parameters or options, 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 into it :

    mkdir hello-world-app && cd hello-world-app
    Copy after login
    Copy after login
  • Use Composer to introduce the console component into our project

    composer require symfony/console
    Copy after login
    Copy after login
  • Then create an entry point for your application, the PHP extension is not Required because we are making this file executable and specifying the environment in the file itself.

    touch HelloWorld
    chmod +X HelloWorld
    Copy after login
    Copy after login
  • Add the following code to the HelloWorld file (I will annotate each line later) and execute HelloWorld in your terminal This application.

    #!/usr/bin/env php
    <?php
    require __DIR__.&#39;/vendor/autoload.php&#39;;
    
    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(&#39;Hello World&#39;, &#39;1.0.0&#39;))
          ->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();
    Copy after login
    Copy after login

Look, that’s it, you have your own HelloWorldConsole program
How to quickly build command line applications using PHP
When no command is specified, HelloWorld outputs a one-screen information prompt by default

Symfony ConsoleThe application provided by the component has several options and commands available out of the box. , such as help, list and --version

Explain the contents of this magical file

OK, let’s do it Take a look at the code in our HelloWorld file.

  1. We introduce autoload.php to use the automatic loading provided by composer and the various functions provided by the console component.

InputInterface and OutputInterface will make input and output functions of the application simple, InputArgument and InputOption will help us handle the options and parameters passed to our HelloWorld application.

<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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;</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>
  1. symphony/consoleInstantiate a new application by name HelloWorld (v1.0.0) , and register our greetCommand.

    <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">(new Application('Hello World', '1.0.0'))     -&gt;register('greet')</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>
  2. We add an optional name parameter (addArgument()) and provide a short description of the parameter. Then, we use this addOption() method to add a say option. Note that options are always optional, but you can specify a value to pass or just use it as a reference to a boolean identifier.

    ->addArgument('name', InputArgument::OPTIONAL, 'Name of the person') 
    ->addOption('say', null, InputOption::VALUE_REQUIRED, 'Custom greeting')
    Copy after login
    Copy after login
  3. setCode()The code in the method will contain the main logic of our application, which will print a greeting to the terminal based on the parameters and options passed. We listen to the $input object, use the getArgument() and getOption() helper methods to get the options and parameters passed to greet, and then , we only need to check which parameters or options are passed, and print the greeting to the console accordingly (using the $output object). This writeln() method can format text according to tags, such as outputting info, error and warning in different colors.

    ->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>");
        }
      })
    Copy after login
    Copy after login
  4. Finally we bootstrap the application and call his method so that he is ready to receive and process the greet command at any time.

    ->getApplication()
    ->run();
    Copy after login
    Copy after login

Now let us take a look at our HelloWorld program in an example

  1. greetDo not pass any parameters and options

How to quickly build command line applications using PHP

  1. greet has an optional name parameter

How to quickly build command line applications using PHP

  1. ##greetCustomize your greeting using the say option

How to quickly build command line applications using PHP

  1. Finally,

    greetCustomize the greeting and greeting person

How to quickly build command line applications using PHP


About the author

Program developer, not limited to language and technology, currently mainly engaged in PHP and front-end development, using Laravel and VueJs. Suitability and sufficiency are the never-ending pursuits.
Personal website: https://www.linganmin.cn

Translator's Note: Some links and picture addresses in this article have been replaced with domestic addresses. Please correct me if there are any translation errors.

Happy Coding!


Original address: How to build a Command Line Application using PHP?
If you are a

Web development engineer, then You must have developed many Web applications using PHP. But do you know how to use PHP to quickly build a command line application (tool)? Below I will show you how to use PHP and a famous ComposerExtension package--Symphony/Console builds a command line application.

Symphony/Console is a

PHP extension package managed with Composer that simplifies creating a beautiful, testable PHP command It provides out-of-the-box functions such as (optional/required) parameter specification and option specification (using - symbols). So, let's start building our application together.

As usual, we will build a "Hello World" console application, but modify it slightly so that it supports a custom greeting (instead of Hello) and can greet someone at will. (instead of world).

This Hello World application will have the following functions:

  1. Provides us with a separate

    greet (greeting) command, which we will use It comes to interact with the application.

  2. greet can accept an optional parameter (name) to print out the person being greeted (default is World).

  3. greetCan accept an option (--say) to change the greeting (default is Hello).

  4. If we give parameters or options, 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 into it :

    mkdir hello-world-app && cd hello-world-app
    Copy after login
    Copy after login
  • Use Composer to introduce the console component into our project

    composer require symfony/console
    Copy after login
    Copy after login
  • Then create an entry point for your application, the PHP extension is not Required because we are making this file executable and specifying the environment in the file itself.

    touch HelloWorld
    chmod +X HelloWorld
    Copy after login
    Copy after login
  • Add the following code to the

    HelloWorld file (I will annotate each line later) and execute HelloWorld in your terminal This application.

    #!/usr/bin/env php
    <?php
    require __DIR__.&#39;/vendor/autoload.php&#39;;
    
    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(&#39;Hello World&#39;, &#39;1.0.0&#39;))
          ->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();
    Copy after login
    Copy after login
Look, that’s it, you have your own

HelloWorldConsole program
How to quickly build command line applications using PHPWhen no command is specified, HelloWorld outputs a one-screen information prompt by default

Symfony ConsoleThe application provided by the component has several options and commands available out of the box. , such as help, list and --version

Explain the contents of this magical file

OK, let’s do it Take a look at the code in our

HelloWorld file.

  1. We introduce

    autoload.php to use the automatic loading provided by composer and the various functions provided by the console component.

##InputInterface

and OutputInterface will make input and output functions of the application simple, InputArgument and InputOption will help us handle the options and parameters passed to our HelloWorld application. <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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;</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>

  1. symphony/console

    Instantiate a new application by name HelloWorld (v1.0.0) , and register our greetCommand. <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">(new Application('Hello World', '1.0.0'))     -&gt;register('greet')</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>

  2. 我们添加一个可选的name参数(addArgument()),并提供参数的简短描述。然后,我们使用这个addOption()方法添加一个say选项。请注意,选项始终是可选的,但您可以指定要传递的值,也可以仅仅将其用作指boolean标识。

    ->addArgument('name', InputArgument::OPTIONAL, 'Name of the person') 
    ->addOption('say', null, InputOption::VALUE_REQUIRED, 'Custom greeting')
    Copy after login
    Copy after login
  3. setCode()方法中的代码会包含我们应用程序的主逻辑,它会根据传递的参数和选项打印一个问候语到终端。我们监听$input对象,使用getArgument()getOption()辅助方法获取传递给greet的选项和参数,然后,我们只需要检查传递了哪些参数或者选项,并相应的(使用$output对象)向控制台输出打印问候语。这个writeln()方法可以根据标签格式化文本,比如输出不同颜色的info,errorwarning

    ->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>");
        }
      })
    Copy after login
    Copy after login
  4. 最后我们引导应用程序并调用他的方法,以便他做好随时接收和处理greet命令。

    ->getApplication()
    ->run();
    Copy after login
    Copy after login

现在让我们在实例中看看我们HelloWorld程序

  1. greet不传递任何参数和选项

How to quickly build command line applications using PHP

  1. greet有一个可选的name参数

How to quickly build command line applications using PHP

  1. greet使用say选项自定义问候语

How to quickly build command line applications using PHP

  1. 最后,greet自定义问候语和问候人

How to quickly build command line applications using PHP

相关推荐:

PHP命令行

关于webpack命令行的详细介绍

关于获取命令行参数的7篇文章推荐


The above is the detailed content of How to quickly build command line applications using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template