Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the PHP command line option parsing library pflag

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to understand the PHP command line option parsing library pflag". The content of the article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn "how to understand the PHP command line option parsing library pflag".

Php-toolkit/pflag is a general command line flag (options and arguments) parsing library written by PHP.

Github warehouse: php-toolkit/pflag (https://github.com/php-toolkit/pflag)

Function description

General command line options and parameter parsers

Support for setting the value data type (int,string,bool,array), and the input value will be formatted automatically

Support setting default values for options / parameters

Support to set multiple short names for one option

Support reading flag values from environment variables

Support setting options / parameters as required (required)

Support setting validator to check input value

Support for automatic rendering of beautiful help messages.

Command line options:

Option begins with-or -, and the first character must be a letter

Those that begin with-- are long options. Eg:-long-long value

The short option that begins with-is-s-a value

Support for defining array options

Eg:-- tag php-- tag go will get $tag = [php, go]

Command line arguments:

All those that cannot satisfy the option are regarded as parameters.

Support for binding named parameters

Support for defining array parameters

Installation

Composer installation

Composer require toolkit/pflagFlags usage

Flags-is a command line flag (options and arguments) parser and manager.

For example code, see example/flags-demo.php

Create a parser

Create and initialize the parser

Use Toolkit\ PFlag\ Flags;require dirname (_ _ DIR__). / test/bootstrap.php';$flags = $_ SERVER ['argv']; / / NOTICE: must shift first element.$scriptFile = array_shift ($flags); $fs = Flags::new (); / / (optional) you can add some custom settings $fs- > setScriptFile ($scriptFile); / * @ see Flags::$settings * / $fs- > setSettings ([' descNlOnOptLen' = > 26]); / /. Define option

Define options-define the supported option settings and parse the input according to the definition

An example of adding an option definition:

Use Toolkit\ PFlag\ Flag\ Option;use Toolkit\ PFlag\ FlagType;use Toolkit\ PFlag\ Validator\ EnumValidator;// add options//-quick add$fs- > addOpt ('age',' asides, 'this is an int option', FlagType::INT); /-use string rules to quickly add options to define $fs- > addOptByRule (' name,n', 'string;this is a string option;true') / /-- add multiple options $fs- > addOptsByRules at a time (['tag,t' = >' strings;array option, allow set multi times','f' = > 'bool;this is an bool option',]) / /-use the array definition / * * @ see Flags::DEFINE_ITEM for array rule * / $fs- > addOptByRule ('name-is-very-lang', [' type' = > FlagType::STRING, 'desc' = >' option name is to lang, desc will print on newline', 'shorts' = >], / / TIP: add validator limit input value. 'validator' = > EnumValidator::new ([' one', 'two',' three']),]); /-use the Option object $opt = Option::new ('str1', "this is string option,\ ndesc has multi line,\ n..."); $opt- > setDefault (' defVal'); $fs- > addOption ($opt); define parameters

Define parameters-define the supported option settings, and the input will be parsed according to the definition

An example of adding a parameter definition:

Use Toolkit\ PFlag\ Flag\ Argument;use Toolkit\ PFlag\ FlagType;// add arguments//-quick add$fs- > addArg ('strArg1',' the is string arg and is required', 'string', true); /-use string rules to quickly add definitions $fs- > addArgByRule (' intArg2', 'int;this is an int arg and with default value;no;89'); / /-use Argument object $arg = Argument::new (' arrArg') / / OR $arg- > setType (FlagType::ARRAY); $arg- > setType (FlagType::STRINGS); $arg- > setDesc ("this is an array arg,\ n allow multi value,\ n must define at last"); $fs- > addArgument ($arg); parse command line input

Finally, call parse () to parse the command line input data

/ /. If (! $fs- > parse ($flags)) {/ / on render help return;} vdump ($fs- > getOpts (), $fs- > getArgs ())

Show help

When you enter-h or-- help, the help information is automatically rendered.

$php example/flags-demo.php-help

Output:

Run the example:

$php example/flags-demo.php-- name inhere-- age 99-- tag go-t php-t java-d one-f arg0 80 arr0 arr1

Output result:

# option data array (6) {["str1"] = > string (6) "defVal" ["name"] = > string (6) "inhere" ["age"] = > int (99) ["tag"] = > array (3) {[0] = > string (2) "go" [1] = > string (3) "php" [2] = > string (4) "java"} ["name-is-very-lang" "] = > string (3)" one "[" f "] = > bool (true)} # Parameter data array (3) {[0] = > string (4)" arg0 "[1] = > int (80) [2] = > array (2) {[0] = > string (4)" arr0 "[1] = > string (4)" arr1 "}} get the input value

It is easy to get a value by using the method getOpt (string $name) getArg ($nameOrIndex).

TIP: the input value will be automatically formatted by the defined data type

Option data

$force = $fs- > getOpt ('f'); / / bool (true) $age = $fs- > getOpt ('age'); / / int (99) $name = $fs- > getOpt (' name'); / / string (inhere) $tags = $fs- > getOpt ('tags'); / / array {"php", "go", "java"}

Parameter data

$arg0 = $fs- > getArg (0); / / string (arg0) / / get an array arg$arrArg = $fs- > getArg (1); / / array {"arr0", "arr1"} / / get value by name$arrArg = $fs- > getArg ('arrArg'); / / array {"arr0", "arr1"} extension: rule definition

Option parameter rules. Use rules to quickly define an option or parameter. [recommended: PHP video tutorial]

String string rules with semicolons; split each part (complete rule: type;desc;required;default;shorts).

Array rules are defined by SFlags::DEFINE_ITEM settings

For supported type constants, please see FlagType::*.

Use Toolkit\ PFlag\ FlagType;$rules = [/ / v: only the value, as the name and using the default type FlagType::STRING / / kmurv: the key is the name, the value can be a string | array 'long,s', / / name = > rule' long,a,b' = > 'int;an int option', / / long is option name, an and b is shorts. 'f' = > FlagType::BOOL, 'str1' = > [' type' = > 'int',' desc' = >'an string option'], 'tags' = >' array; an array option', / / can also: ints, strings' name' = > 'type;the description message;required;default', / / with desc, default, required]

For option

Option allows you to set the short name shorts

TIP: for example, long,a,b-long is the name of the option. The rest of the aformab is its short option name.

For parameters

Parameter has no alias or short name

Array parameters are only allowed to be defined at the end

Array definition item

Constant Flags::DEFINE_ITEM:

Public const DEFINE_ITEM = ['name' = >', 'desc' = >', 'type' = > FlagType::STRING,' helpType' = >'', / / use for render help / / 'index' = > 0, / / only for argument' required' = > false, 'default' = > null,' shorts' = > [], / / only for option / / value validator' validator' = > null / / 'category' = > null] Custom settings parsing settings / /-options parsing settings-/ * Stop parse option on found first argument. * *-Useful for support multi commands. Eg: `top-- opt... Sub-- opt... `* * @ var bool * / protected $stopOnFistArg = true; / * Skip on found undefined option. * *-FALSE will throw FlagException error. *-TRUE will skip it and collect as raw arg, then continue parse next. * * @ var bool * / protected $skipOnUndefined = false; / /-Parameter resolution settings-/ * Whether auto bind remaining args after option parsed * * @ var bool * / protected $autoBindArgs = true; / * Strict match args number. * if exist unbind args, will throw FlagException * * @ var bool * / protected $strictMatchArgs = false; rendering help Settings

Support some settings for render help

/ /-settings for built-in render help-/ * automatic rendering help information when entering the'- hashes,'--help' option * * @ var bool * / protected $autoRenderHelp = true / * display the data type on the rendering help * * if False: * *-o,-- opt Option desc * * if True: * *-o,-- opt STRING Option desc * * @ var bool * / protected $showTypeOnHelp = true / * it will be called before printing the help message * * @ var callable * / private $beforePrintHelp

Customize the rendering of help messages:

$fs- > setHelpRenderer (function (\ Toolkit\ PFlag\ FlagsParser $fs) {/ / render help messages}); unit test phpunit-- debug

Test with coverage:

Phpdbg-qrr $(which phpunit)-- coverage-text projects that use pflag

Check out these projects, which use github.com/php-toolkit/pflag:

Inhere/console Full-featured php command line application library.

Kite Kite is a tool for help development.

More, please see Packagist

Github warehouse: php-toolkit/pflag (https://github.com/php-toolkit/pflag)

Thank you for your reading, the above is the content of "how to understand the PHP command line option parsing library pflag". After the study of this article, I believe you have a deeper understanding of how to understand the PHP command line option parsing library pflag, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report