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).
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.
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__.'/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
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 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.
symphony/console
Instantiate a new application by name HelloWorld (v1.0.0)
, and register our greet
Command.
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')
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>"); } })
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();
greet
Do not pass any parameters and options
greet
has an optional name
parameter
##greetCustomize your greeting using the
say option
greetCustomize the greeting and greeting person
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.
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).
greetCan accept an option (
--say) to change the greeting (default is Hello).
Hello World message by default.
cd into it :
mkdir hello-world-app && cd hello-world-app
composer require symfony/console
touch HelloWorld chmod +X HelloWorld
HelloWorld file (I will annotate each line later) and execute
HelloWorld 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();
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.
autoload.php to use the automatic loading provided by
composer and 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. <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>
Instantiate a new application by name HelloWorld (v1.0.0)
, and register our greet
Command. <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'))
->register('greet')</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>
我们添加一个可选的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();
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!