shso / cli
有用的 CLI 相关函数
v1.1.1
2019-05-22 00:00 UTC
Requires
- php: >7.1
- illuminate/support: ^5.8
This package is auto-updated.
Last update: 2024-09-15 21:31:45 UTC
README
增强 PHP CLI 脚本体验。
安装
使用 Composer
$ composer require shso/cli
Composer 会自动加载库。
手动
下载脚本
$ curl -fL -O https://github.com/ShahinSorkh/php-cli/raw/master/src/cli.php
# Or using wget
$ wget https://github.com/ShahinSorkh/php-cli/raw/master/src/cli.php
导入到您的脚本中
require_once './cli.php';
脚本使用
假设以下 CLI
$ php script.php -f --action ACTION -- ARG1 ARG2 ARG3
计数参数
cli\argc(); // returns 3
获取参数
cli\arg(); // returns ['script.php', 'ARG1', 'ARG2', 'ARG3'] cli\arg(2); // returns 'ARG2' cli\arg(4, 'foo'); // returns 'foo'
获取选项
cli\opt(); // returns ['f' => true, 'action' => 'ACTION'] cli\opt('f'); // returns true cli\opt('action'); // returns 'ACTION' cli\opt('q'); // returns null cli\opt('foo', 'bar'); // returns 'bar'
定义使用
您可以使用 strict 选项和参数定义严格的使用。要做到这一点,您应该使用 cli\usage()
方法,该方法接受一个数组作为参数,其中包含可能的键 args
、opts
、desc
。
定义参数
参数可以是可选的。
cli\usage([ 'args' => [ 'REQUIRED_ARG', '[OPTIONAL_ARG]' ], ]);
定义选项
选项可以是可选的,并且可以接受参数。此外,选项可以是短选项或长选项。
cli\usage([ 'opts' => [ '-f' => null, // optional, without arg, short '*c' => null, // required, without arg, short '-o' => 'OPT_ARG', // optional, with arg, short '-no-dev' => null, // optional, without arg, long '*config' => 'CONFIG', // required, with arg, long ], ]);
定义附加描述
如果您需要描述有关选项或参数的信息,您可以这样做。
cli\usage([ 'args' => [ 'CONFUSING_ARG' ], 'opts' => [ '-f' => null, ], 'desc' => [ 'CONFUSING_ARG' => 'Some descriptions that make the arg not confusing!', '-f' => 'Describe -f option can force the operation or whatever.', ], ]);
命令行使用
此包支持以下语法
$ php script.php --opt --opt-with-arg OPT_ARG -- ARG [OPTIONAL_ARG]
传递参数
- 参数必须是最后一个值。这意味着以下语法是不可接受的
$ php script.php ARG1 --opt1 ARG2 --opt2 OPT2_ARG ARG3 ARG4
检测到任何参数时,该参数之后的所有值都被视为参数。这意味着以下所有值 ARG1
、--opt1
、ARG2
、--opt2
、OPT2_ARG
、ARG3
、ARG4
都是单独的参数。
- 每个选项之后的每个非选项值都被视为该选项的参数。这意味着在以下语法中,
ARG1
将作为--op1
选项的值可用(见下文)
$ php script.php --op1 ARG1
如果您需要一个布尔选项和一些参数,请在参数之前使用 --
。例如
$ php script.php --op1 -- ARG1
- 如果您需要从
stdin
获取输入,请使用-
。例如
$ php script.php - < somefile.txt $ cat somefile.txt | php script.php -
您可以同时传递其他参数和选项。
传递选项
每个以 -
开头的值,在第一个检测到的参数之前,都是一个选项。选项可以作为其参数获取额外的值。例如
$ php script.php -f --file SOME_FILE $ php customzipcompress.php --rm --compression best -f FILE1,FILE2 -d DIR1
如果您要传递参数,则选项 必须 以 --
结尾。例如
$ php script.php -t -g OPT_ARG -- ARG1