国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
After writing the basic "Hello World" script, we can set its permissions to allow execution and run it on the command line.
Supplementary description of the menu style
Read a line of users to enter
Set text style
So far, our example script is shown below:
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:
Home Backend Development PHP Tutorial php: writing command-line applications with macrame. pt 1

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

Jan 30, 2025 am 04:07 AM

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

composer require gbhorwood/macrame
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.

#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 實(shí)例化 Macrame 對(duì)象。
// 參數(shù)是 ps(1) 所見的腳本名稱
$macrame = new Macrame("示例 Macrame 腳本");

// 強(qiáng)制僅在命令行上執(zhí)行腳本時(shí)才運(yùn)行腳本
if ($macrame->running()) {

    // 驗(yàn)證主機(jī)系統(tǒng)是否可以運(yùn)行 Macrame 腳本。失敗時(shí)退出
    $macrame->preflight();

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

    // 清潔退出
    $macrame->exit();
}
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.

<<>
#!/usr/bin/env php

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.

composer require gbhorwood/macrame

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;
#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 實(shí)例化 Macrame 對(duì)象。
// 參數(shù)是 ps(1) 所見的腳本名稱
$macrame = new Macrame("示例 Macrame 腳本");

// 強(qiáng)制僅在命令行上執(zhí)行腳本時(shí)才運(yùn)行腳本
if ($macrame->running()) {

    // 驗(yàn)證主機(jī)系統(tǒng)是否可以運(yùn)行 Macrame 腳本。失敗時(shí)退出
    $macrame->preflight();

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

    // 清潔退出
    $macrame->exit();
}

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 <讀>
#!/usr/bin/env php
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.

$macrame = new Macrame("示例 Macrame 腳本");
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.

if ($macrame->running())

? 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:

$macrame->preflight();

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

first
$macrame->exit();
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
chmod 755 ./examplescript.php
./examplescript.php
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.

./examplescript.php --version
# 或
./examplescript.php -v
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:

composer require gbhorwood/macrame

The core function here is to call the following:

#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 實(shí)例化 Macrame 對(duì)象。
// 參數(shù)是 ps(1) 所見的腳本名稱
$macrame = new Macrame("示例 Macrame 腳本");

// 強(qiáng)制僅在命令行上執(zhí)行腳本時(shí)才運(yùn)行腳本
if ($macrame->running()) {

    // 驗(yàn)證主機(jī)系統(tǒng)是否可以運(yùn)行 Macrame 腳本。失敗時(shí)退出
    $macrame->preflight();

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

    // 清潔退出
    $macrame->exit();
}

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.

#!/usr/bin/env php

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:

$macrame = new Macrame("示例 Macrame 腳本");

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: <>

if ($macrame->running())
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:

$macrame->preflight();
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 ().

$macrame->exit();
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.

composer require gbhorwood/macrame

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: <>

#!/usr/bin/env php
<?php require __DIR__ . '/vendor/autoload.php';

use Gbhorwood\Macrame\Macrame;

// 實(shí)例化 Macrame 對(duì)象。
// 參數(shù)是 ps(1) 所見的腳本名稱
$macrame = new Macrame("示例 Macrame 腳本");

// 強(qiáng)制僅在命令行上執(zhí)行腳本時(shí)才運(yùn)行腳本
if ($macrame->running()) {

    // 驗(yàn)證主機(jī)系統(tǒng)是否可以運(yùn)行 Macrame 腳本。失敗時(shí)退出
    $macrame->preflight();

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

    // 清潔退出
    $macrame->exit();
}
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
#!/usr/bin/env php

So far, our example script is shown below:

What is the next
$macrame = new Macrame("示例 Macrame 腳本");

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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

See all articles