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 Composer
Extension 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:
Provides us with a separate
greet
(greeting) command, which we will use It comes to interact with the application.greet
can accept an optional parameter (name
) to print out a person being greeted (default is World).greet
Can accept an option (--say
) to change the greeting (default is Hello).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 executeHelloWorld in your terminal
This application.#!/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();
Look, that’s it, you have your own HelloWorld
Console program
When no command is specified, HelloWorld outputs a one-screen information prompt by default
Symfony Console
The 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.
We introduce
autoload.php
to use the automatic loading provided bycomposer
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">(new Application('Hello World', '1.0.0')) ->register('greet')</pre>symphony/console
Instantiate a new application by nameHelloWorld (v1.0.0)
, and register ourgreet
Command. -
We add an optional
name
parameter (addArgument()
) and provide a short description of the parameter. Then, we use thisaddOption()
method to add asay
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')
-
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 thegetArgument()
andgetOption()
helper methods to get the options and parameters passed togreet
, 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). Thiswriteln()
method can format text according to tags, such as outputtinginfo
,error
andwarning
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>"); } })
-
Finally we bootstrap the application
and call his
method so that he is ready to receive and process thegreet
command at any time.->getApplication() ->run();
Now let us take a look at our HelloWorld program in an example
greet
Do not pass any parameters and options
greet
has an optionalname
parameter
##greet
Customize your greeting using the
sayoption
- Finally,
greet
Customize the greeting and greeting person
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.cnTranslator'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!
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.
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.
- Provides us with a separate
greet
(greeting) command, which we will use It comes to interact with the application.
greet
can accept an optional parameter (
name) to print out the person being greeted (default is World).
greet
Can accept an option (
--say) to change the greeting (default is Hello).
- If we give parameters or options, the program will output a
Hello World
message by default.
- 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 terminalThis application.
#!/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();
HelloWorldConsole program
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
HelloWorld file.
- We introduce
autoload.php
to use the automatic loading provided by
composerand the various functions provided by the console component.
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>
- symphony/console
Instantiate a new application by name
HelloWorld (v1.0.0)
, and register ourgreet
Command.<pre class="brush:php;toolbar:false">(new Application('Hello World', '1.0.0')) ->register('greet')</pre>
-
我们添加一个可选的
name
参数(addArgument()
),并提供参数的简短描述。然后,我们使用这个addOption()
方法添加一个say
选项。请注意,选项始终是可选的,但您可以指定要传递的值,也可以仅仅将其用作指boolean标识。->addArgument('name', InputArgument::OPTIONAL, 'Name of the person') ->addOption('say', null, InputOption::VALUE_REQUIRED, 'Custom greeting')
-
setCode()
方法中的代码会包含我们应用程序的主逻辑,它会根据传递的参数和选项打印一个问候语到终端。我们监听$input
对象,使用getArgument()
和getOption()
辅助方法获取传递给greet
的选项和参数,然后,我们只需要检查传递了哪些参数或者选项,并相应的(使用$output
对象)向控制台输出打印问候语。这个writeln()
方法可以根据标签格式化文本,比如输出不同颜色的info
,error
和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>"); } })
-
最后我们引导应用程序
并调用他的
方法,以便他做好随时接收和处理greet
命令。->getApplication() ->run();
现在让我们在实例中看看我们HelloWorld程序
greet
不传递任何参数和选项
greet
有一个可选的name
参数
greet
使用say
选项自定义问候语
最后,
greet
自定义问候语和问候人
相关推荐:
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!

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

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

卸载程序的文件名是“uninstall.exe”或“uninst.exe”,是用以协助使用者将软件自电脑中删除的一种电脑软件。使用方法:1、在文件资源管理器中挖掘并导航到应用程序EXE文件所在的文件路径;2、通过文件路径打开应用程序的安装目录,找到“uninstall.exe”文件;3、双击卸载文件“uninstall.exe”即可开始程序删除过程。
![如何修复 Windows 11 上的应用程序无法打开问题 [已解决]](https://img.php.cn/upload/article/000/465/014/168300240866363.png)
微软最新发布的Windows11,已经证明是Windows10的更好版本,其结构变化、更人性化、重新排列的任务栏等。尽管Windows11是其中一个优秀的版本。许多Windows用户注意到他们的Windows11PC上存在一个不寻常的问题,他们无法启动大多数Windows11应用程序。无论他们尝试启动应用程序多少次,它只是简单地崩溃并且无法在系统上打开。突然发生这种情况可能有很多原因,下面列出了一些原因。Windows更新服务已停止。对系统的病毒攻击。系统上的用户帐户存

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

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

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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
The latest (2018.2.1) professional PHP integrated development tool
