Home > Backend Development > PHP Tutorial > php: writing command-line applications with macrame. pt 1

php: writing command-line applications with macrame. pt 1

Patricia Arquette
Release: 2025-01-30 04:07:09
Original
576 people have browsed it

PHP is not a script language that has attracted much attention, but this is a pity, because PHP has many ideals that make it the ideal choice to write a terminal application.

This series of articles will introduce how to use the Macrame library to write an interactive command line script. We will gradually complete a sample item. The script obtains the list of Mastodon user followers from beginning to end, and covers the following topics: obtain and verify user input, build interactive menu, handle command line parameters, security access files, set output text styles, and Run the function in the background when the animation loader is displayed to the user.

For more information about Macrame, visit the document site.

Example items

The project we will complete is a simple command line script that is used to return the list of followers of Mastodon users. Run the script as shown below:

In the run script operation php: writing command-line applications with macrame. pt 1

The user selects the required MASTODON instance from the dynamic menu, enters the user name as a free text, and the script displays the animation loader when obtaining the data. The output is a beautiful ASCII style table.

For anyone who wants to skip this step, the complete source code of this project is provided in the form of GIST.

Overview

In this section, how will we introduce:

Install Macrame

    Create a blank script
  • Read the command line parameters
  • Create a dynamic menu
  • Read a line of user input (optional verification)
  • Set output text style
  • Install Macrame
Install Macrame:

Create a script framework

<code class="language-bash">composer require gbhorwood/macrame</code>
Copy after login
Copy after login
Copy after login
Copy after login
After installing Macrame, we can set up a basic "Hello World" script and use it as our starting model. Although technically, this framework is not necessary, but use it will make our script safer and more standardized. Let's take a look at the code:

Although there are not many code lines, many things happen here. Let's take a closer look.

<code class="language-php">#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 实例化 Macrame 对象。
// 参数是 ps(1) 所见的脚本名称
$macrame = new Macrame("示例 Macrame 脚本");

// 强制仅在命令行上执行脚本时才运行脚本
if ($macrame->running()) {

    // 验证主机系统是否可以运行 Macrame 脚本。失败时退出
    $macrame->preflight();

    // 将文本输出到 STDOUT
    $macrame->text("Hello World")->write();

    // 清洁退出
    $macrame->exit();
}</code>
Copy after login
Copy after login
Copy after login
Copy after login
This line is "shebang". Basically, it tells our Linux operating system which interpreter to run this script. This allows us to run scripts without having to type PHP first. Shebang must be

the first line of the file, even before & lt;? PHP.

<code class="language-php">#!/usr/bin/env php</code>
Copy after login
Copy after login
Copy after login
Copy after login

Here, we create a Macrame object that we will use it in the rest of the script. Very standard content. The only interesting part is the parameter. This is the name of the operating system that will give us the script. For example, if we run PS to display the running process list, our script will display this name.
This statement ensures that all the code in the block is executed only when the script is run on the command line.

<code class="language-bash">composer require gbhorwood/macrame</code>
Copy after login
Copy after login
Copy after login
Copy after login

When we write PHP for the command line, our control of the environment is not as much as web servers we have and manage. The preflicht () calls the local PHP environment. If it does not meet the minimum requirements, it will terminate the script and display the error message. The minimum requirements are:

    PHP 7.4
  • POSIX extension
  • MBSTRING Extension
Note:

Although Macrame runs on PHP 7.4 and 8.0, because PHP has changed in 8.1, The symbol string may not be aligned correctly in the output.

This will exit the script cleanly and return the success code of 0. In addition, any temporary file created during the execution will be automatically deleted. It is best to use the exit () function of the Macrame instead of the DIE () of PHP;
<code class="language-php">#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 实例化 Macrame 对象。
// 参数是 ps(1) 所见的脚本名称
$macrame = new Macrame("示例 Macrame 脚本");

// 强制仅在命令行上执行脚本时才运行脚本
if ($macrame->running()) {

    // 验证主机系统是否可以运行 Macrame 脚本。失败时退出
    $macrame->preflight();

    // 将文本输出到 STDOUT
    $macrame->text("Hello World")->write();

    // 清洁退出
    $macrame->exit();
}</code>
Copy after login
Copy after login
Copy after login
Copy after login

Run hello world

After writing the basic "Hello World" script, we can set its permissions to allow execution and run it on the command line.

Read the parameters
<code class="language-php">#!/usr/bin/env php</code>
Copy after login
Copy after login
Copy after login
Copy after login
Macrame provides a set of tools for analysis and reading command line parameters. Let's start with some simple things: Get the version number when using the following command to call the script:

For this situation, we only need to check whether these parameters exist.

<code class="language-php">$macrame = new Macrame("示例 Macrame 脚本");</code>
Copy after login
Copy after login
Copy after login
We can achieve this purpose by calling the ARGS () method on the Macrame object. This method returns an object that contains all scripts and we can check many methods. To test whether the parameters exist, we can use the Exist () method, as shown below:

Exist () method return to Boolean.

<code class="language-php">if ($macrame->running())</code>
Copy after login
Copy after login

? Macrame calls are designed to perform chain calls.

The command line parameters can also be used to assign a value for variables. For example, to set the user name value, we may hope that users can call the script like this:

To get the value of this parameter in our script, we can use the first () method provided by ARGS (), as shown below:

<code class="language-php">$macrame->preflight();</code>
Copy after login
Copy after login

As the name suggests, the first () method returns the

first
<code class="language-php">$macrame->exit();</code>
Copy after login
Copy after login
value of the parameter. If we call the script like this:

Then first () will return the "firstuser" value. If we want the last value, we can call Last (). If we want

all
<code class="language-bash">chmod 755 ./examplescript.php
./examplescript.php</code>
Copy after login
as an array, we will use all ().

Putting all these together, our script looks like this now:

The full method list of handling command line parameters is introduced in the Macrame parameter document.

<code class="language-bash">./examplescript.php --version
# 或
./examplescript.php -v</code>
Copy after login
Create a dynamic menu

We also hope to allow users to use our script in an interactive manner. If they do not pass the parameters on the command line, we will prompt them to enter the data. For MASTODON examples, we will use the menu.

Macrame menu is dynamic; users can use the arrow key to move up and down the list, and then press the

key to select.

Let's write a function that displays the menu to the user and return the value of the selected value:

<code class="language-bash">composer require gbhorwood/macrame</code>
Copy after login
Copy after login
Copy after login
Copy after login

The core function here is to call the following:

<code class="language-php">#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 实例化 Macrame 对象。
// 参数是 ps(1) 所见的脚本名称
$macrame = new Macrame("示例 Macrame 脚本");

// 强制仅在命令行上执行脚本时才运行脚本
if ($macrame->running()) {

    // 验证主机系统是否可以运行 Macrame 脚本。失败时退出
    $macrame->preflight();

    // 将文本输出到 STDOUT
    $macrame->text("Hello World")->write();

    // 清洁退出
    $macrame->exit();
}</code>
Copy after login
Copy after login
Copy after login
Copy after login

We provide a string array as the menu option, and a optional menu title text for Menu ()-& GT; Internet (), and the menu will automatically display it to users. The user's choice will be returned as a string.

By adding to Erase () to our chain, you can also choose to erase the menu from the screen after the user makes a choice. This method is optional, but it can indeed be tidy.

After obtaining the menu function, we can modify the way to get the Mastodon instance. We will try to read it from the command line parameters. If no value is passed, the menuinstance () function is called.

<code class="language-php">#!/usr/bin/env php</code>
Copy after login
Copy after login
Copy after login
Copy after login

Supplementary description of the menu style

By default, Macrame uses the default style and color of the terminal to display the menu, and the project that highlights the displayed display is set to reverse display. If necessary, we can change this setting by adding some additional functions to our chain. For example, if we want to highlight the displayed items displayed as a thick red text, we can write this:

<code class="language-php">$macrame = new Macrame("示例 Macrame 脚本");</code>
Copy after login
Copy after login
Copy after login

The menu document pages a complete overview of all methods that can be used to customize the color, style and alignment method of custom menu.

Read a line of users to enter

Next, we will modify the way to obtain the username so that it will also accept interactive input. In this case, we will use input ()-& gt; readline () to read the user input text string. The following is the function:

<code class="language-php">if ($macrame->running())</code>
Copy after login
Copy after login
The last line of this function is where we inquire with users. Readline () method accepts optional $ Prompt parameters; the text we show to users tells them what they should enter. The return value is the string entered by the user.

Supplementary description of input verification

Users will make mistakes. This is why input verification is important.

Macrame comes with many preset methods to verify the input. We can add any number of verifications to our chain. If any verification device fails, the system will prompt the user to enter again. Input ()-& gt; Readline () function will return the value only after all verifications pass.

Let's take a look at an example:

<code class="language-php">$macrame->preflight();</code>
Copy after login
Copy after login
Here, we apply two verification tests: the text must be four or more characters, and cannot include the "@" symbol. For these two verification methods, the second parameter is the error message we will display to the user if the verification fails.

Macrame input document page provides a complete list of all pre -constructive verification functions. If we want to write our own custom verification device, it is also introduced in it.

What about the output of "point -like back display"?

If our user enters sensitive data, such as a password, we may not want to show their keys back to the terminal to avoid being seen by the spymen.

In order to solve this problem, Macrame provides the "point -shaped back display" version of Readline (), called Readpassword ().

<code class="language-php">$macrame->exit();</code>
Copy after login
Copy after login
Readpassword () Each button read will be revealed in the form of a star number.

Set text style

In the example of how to read a line of user text, we have seen a large number of codes used to set a prompt text style. Let's study it in detail.

Macrame allows the use of ANSI code to set the terminal text output style, which allows us to apply the style and color of the thick body and oblique body to our text.

We can perform this operation in our script through two ways. There are some ways, such as style () and colour () (or color ()), or we can use the basic text mark system.

Let's first look at the method.

<code class="language-bash">composer require gbhorwood/macrame</code>
Copy after login
Copy after login
Copy after login
Copy after login

Here, we use Macrame's Text () method to create a "text" object, then apply style and color, and finally use get () to return it as a string.

Please note that style and color methods are applied to all texts in the string. If we want to mix style and color text with pure text, we will have to create many sub -string and connect them together. This may be very troublesome, especially when dealing with a large number of texts.

or, we can use Macrame's markup system to simplify the text style settings. This is an example:

<code class="language-php">#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 实例化 Macrame 对象。
// 参数是 ps(1) 所见的脚本名称
$macrame = new Macrame("示例 Macrame 脚本");

// 强制仅在命令行上执行脚本时才运行脚本
if ($macrame->running()) {

    // 验证主机系统是否可以运行 Macrame 脚本。失败时退出
    $macrame->preflight();

    // 将文本输出到 STDOUT
    $macrame->text("Hello World")->write();

    // 清洁退出
    $macrame->exit();
}</code>
Copy after login
Copy after login
Copy after login
Copy after login
The text between and

marks will be thickened (of course). The document lists the complete list of all the marks. One thing to note is that the mark will turn off all previous marks. This is due to the behavior of the ANSI transfer code.

This means that nested marks will not work as we expect. For example, in this example, the first mark will be closed

and

mark:

The current script
<code class="language-php">#!/usr/bin/env php</code>
Copy after login
Copy after login
Copy after login
Copy after login

So far, our example script is shown below:

What is the next
<code class="language-php">$macrame = new Macrame("示例 Macrame 脚本");</code>
Copy after login
Copy after login
Copy after login

So far, we have introduced reading command line parameters, obtaining user input from menu and text, and making some basic text styles for the output. In the next article, we will introduce:

Run the function in the background when the animation loader is displayed to the user
  • Write the file safely
  • Output of array data as a good format output
  • Pagling display long output
  • Basic notification level output
? This article was originally published in Grant Horwood Technology Blog

The above is the detailed content of php: writing command-line applications with macrame. pt 1. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template