php-console icon indicating copy to clipboard operation
php-console copied to clipboard

如何动态提取参数?

Open lkeme opened this issue 3 years ago • 8 comments

WIKI没看到相应的文档

  1. param*是动态的 如何获取使用?
app.php a:{param1} b:{param2}
  1. 如何忽略一些固定位置的argv
app.php {fixed_position}  test:test
...
[ERROR] The command 'fixed_position' is not exists!

lkeme avatar May 28 '22 11:05 lkeme

  1. 参数是根据位置读取的,推荐使用选项 --name value
  2. app.php 是应用入口,接下来的就是 命令名称 这是必须的

关于控制台命令,可以再看下文档,还有我新增了一些使用说明:

https://github.com/inhere/php-console/wiki/about-console-command

如果你只想构建一个简单的命令可以使用我的 php-toolkit/pflag 库, php-console 是基于它构建复杂应用的。

https://github.com/php-toolkit/pflag/blob/main/README.zh-CN.md#%E5%88%9B%E5%BB%BA%E7%AE%80%E5%8D%95%E7%9A%84%E7%8B%AC%E7%AB%8B%E5%91%BD%E4%BB%A4%E6%88%96%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F

inhere avatar May 28 '22 17:05 inhere

console比较符合需要,有使用到Controllers Commands的架构

php app.php --name {value} test:test

其他都比较好,需求是用想省略参数,--name是固定位置(都在app.php后面一位),且是必要参数。

php app {value} test:test

可用其他方案实现需求,但会出现 is not exists

另外才发现,想用到的好几个库都是你的,slog、config、stdlib、console...

lkeme avatar May 29 '22 04:05 lkeme

命令行应用应当遵循通用的命令规范,方便使用

image

最后的参数是可以省略的,console 里可以按位置给参数命名,可以设置非必须,用的时候使用名字获取就行

来自 wiki https://github.com/inhere/php-console/wiki/v4-create-command

    /**
     * @param FlagsParser $fs
     *
     * @return void
     */
    protected function configFlags(FlagsParser $fs): void
    {
        $fs->addOptByRule('search, s', 'string;input keywords for search');

        // 绑定参数 非必须的 可以不传,获取到就是空string
        $fs->addArg('keywords', 'the keywords for search or show docs', 'string');
    }

    protected function execute(Input $input, Output $output)
    {
        $keywords = $this->flags->getOpt('search');

	$name = $this->flags->getArg('keywords');
	// 也可以按位置取
	// $name = $this->flags->getFirstArg();
    }


哈哈 对的。我建了好几个组织,分别放不同语言、类型的库和包

inhere avatar May 29 '22 04:05 inhere

来自 wiki: https://github.com/inhere/php-console/wiki/about-console-command

image

inhere avatar May 29 '22 05:05 inhere

命令行“遵循通用的命令规范”看起来是后面支持的吗?从低版本升级到现在的版本“4.1.6”,发现如果 ARGUMENTS 在 --OPTIONS 前面,无法获取到 --OPTIONS 的值

deliangyang avatar Mar 26 '24 09:03 deliangyang

命令行“遵循通用的命令规范”看起来是后面支持的吗?从低版本升级到现在的版本“4.1.6”,发现如果 ARGUMENTS 在 --OPTIONS 前面,无法获取到 --OPTIONS 的值

按规范 ARGS 只能在 OPTIONS 后面,遇到 args 就会停止解析。

inhere avatar Mar 27 '24 02:03 inhere

自从升级该依赖到最新版本后,给我的同事带来了不少的困恼。以前可选和参数的顺序可以互换,升级之后,顺序必须遵循:“可选”后面跟随“参数”。

终于在 GUN 找到了官方解释 Argument-Syntax

The argument -- terminates all options; any following arguments are treated as non-option arguments, even if they begin with a hyphen.

deliangyang avatar Apr 26 '24 07:04 deliangyang

:) 之前没按严格规范解析,用着是灵活简单一些。 但遇到一些特殊场景不能处理,可能会导致解析出错误的结果。

inhere avatar Apr 27 '24 12:04 inhere