search
HomeBackend DevelopmentPHP TutorialHow to quickly build command line applications 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 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
  • Use Composer to introduce the console component into our project

    composer require symfony/console
  • 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
  • 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();

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.

<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>
  1. symphony/consoleInstantiate a new application by name HelloWorld (v1.0.0) , and register our greetCommand.

    <pre class="brush:php;toolbar:false">(new Application('Hello World', '1.0.0'))     -&gt;register('greet')</pre>
  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')
  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>");
        }
      })
  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();

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
  • Use Composer to introduce the console component into our project

    composer require symfony/console
  • 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
  • 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();
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. <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>

  1. symphony/console

    Instantiate a new application by name HelloWorld (v1.0.0) , and register our greetCommand. <pre class="brush:php;toolbar:false">(new Application('Hello World', '1.0.0'))     -&gt;register('greet')</pre>

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

    ->addArgument('name', InputArgument::OPTIONAL, 'Name of the person') 
    ->addOption('say', null, InputOption::VALUE_REQUIRED, 'Custom greeting')
  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>");
        }
      })
  4. 最后我们引导应用程序并调用他的方法,以便他做好随时接收和处理greet命令。

    ->getApplication()
    ->run();

现在让我们在实例中看看我们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!

Statement
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
PHP实现MVVM架构:基本原理及应用PHP实现MVVM架构:基本原理及应用Jun 18, 2023 am 08:54 AM

随着Web应用程序的快速发展,越来越多的开发者将目光投向了各种新兴的Web开发框架和架构设计模式。其中一个备受瞩目的设计模式就是MVVM(ModelViewViewModel)架构模式。MVVM采用了一种现代化的设计模式,通过将UI和业务逻辑相分离,使得开发人员能够更好地管理和维护应用程序。此外,MVVM减少了不必要的耦合,提高了代码的可重用性和灵活性,

msedge.exe是什么应用程序msedge.exe是什么应用程序Sep 09, 2022 pm 02:37 PM

“msedge.exe”指的是“Microsoft Edge”网页浏览器软件;“Microsoft Edge”是由Microsoft开发的网页浏览器,该浏览器在2015年被正式命名,并且内置在了Windows10版本中;该浏览器与IE浏览器相比,Edge将支持现代浏览器功能,比如扩展。

卸载程序的文件名是什么卸载程序的文件名是什么Oct 21, 2022 pm 02:05 PM

卸载程序的文件名是“uninstall.exe”或“uninst.exe”,是用以协助使用者将软件自电脑中删除的一种电脑软件。使用方法:1、在文件资源管理器中挖掘并导航到应用程序EXE文件所在的文件路径;2、通过文件路径打开应用程序的安装目录,找到“uninstall.exe”文件;3、双击卸载文件“uninstall.exe”即可开始程序删除过程。

如何修复 Windows 11 上的应用程序无法打开问题 [已解决]如何修复 Windows 11 上的应用程序无法打开问题 [已解决]May 02, 2023 pm 12:40 PM

微软最新发布的Windows11,已经证明是Windows10的更好版本,其结构变化、更人性化、重新排列的任务栏等。尽管Windows11是其中一个优秀的版本。许多Windows用户注意到他们的Windows11PC上存在一个不寻常的问题,他们无法启动大多数Windows11应用程序。无论他们尝试启动应用程序多少次,它只是简单地崩溃并且无法在系统上打开。突然发生这种情况可能有很多原因,下面列出了一些原因。Windows更新服务已停止。对系统的病毒攻击。系统上的用户帐户存

explorer.exe应用程序错误如何解决explorer.exe应用程序错误如何解决Jun 21, 2023 pm 02:14 PM

explorer.exe应用程序错误的解决办法:1、按下键盘上的“win”+“R”组合键,再打开的运行窗口中输入命“inetcpl.cpl”;2、在上方选择“高级”选项卡,在下方点击“重置”;3、在弹出来的窗口中,勾选“删除个人设置”,勾选后点击下面的“重置”。如果以上操作无法解决问题,请检查电脑是否有木马,这个时候建议重装系统,安装一个原版或者纯净版的系统。

使用PHP和OpenLayers创建地图应用程序使用PHP和OpenLayers创建地图应用程序May 11, 2023 pm 08:31 PM

随着Internet的发展,越来越多的应用程序需要实现地图可视化展示。本文将介绍如何使用PHP和OpenLayers创建地图应用程序。一、OpenLayers介绍OpenLayers是一个JavaScript开源库,可以展示动态地图。除了展示标准的WMS、WFS和GoogleMaps,OpenLayers还可以展示自定义的地图,可以展示矢量数据,支持地图放

如何在 Windows 11 中重新安装邮件应用程序如何在 Windows 11 中重新安装邮件应用程序Apr 14, 2023 pm 03:19 PM

&lt;p&gt;&lt;strong&gt;邮件应用程序&lt;/strong&gt;是Windows11内置的一个非常有用的电子邮件客户端。它允许您从一个位置管理所有邮件帐户。虽然Mail应用程序非常有用,但有时可能需要重置,有时也需要重新安装,原因有多种。在本文中,我们将通过一些简单的步骤说明如何从Windows11轻松卸载Mail应用程序,以及如何轻松地从MicrosoftStore将其取回。&lt;/p&gt;&l

基于Django建立Web GIS应用程序基于Django建立Web GIS应用程序Jun 17, 2023 pm 01:12 PM

随着全球定位系统(GPS)和卫星影像技术的飞速发展,地理信息系统(GIS)已经成为了一个重要的应用领域。GIS不仅限于地图制作和分析,也被广泛应用于环境管理、土地管理、城市规划等领域。而WebGIS应用程序的开发,可以使得用户在任何地点、任何时间、通过任何设备进行GIS数据的查询、分析和管理,具有极大的应用前景。Django是一个基于Python语言的We

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool