我有一个PHP命令行脚本,可以将作业名称作为参数启动到作业服务器上。 作业名称是有命名空间的,例如Foo:Bar_Baz_JobName。 我是否可以实现自动补全功能,就像在bash中键入文件名的前几个字母并按下Tab键一样自动完成文件名。 我知道这可以做到,因为在ubuntu上使用apt-get时,tab自动完成功能是有效的,但我不知道是否可以在PHP中实现。
readline_completion_function
。使用方法非常简单;调用readline_completion_function
并传入一个参数,即处理自动补全的回调函数。回调函数将前几个字母(基本上是按下TAB之前键入的任何内容)作为输入,并应返回可能匹配的数组。我认为,考虑到您想要的交互类型(apt-get自动完成),这种方法并不好。
事实上,在获得自动完成函数之前,您必须运行脚本,然后才能访问自动完成函数。
自动完成函数是部分的。因此,它类似于bash自动完成而不是zsh。
在shell中:
➜ ~ php test.php (enter)
Custom command: (tab)
a b c
Custom command: (tab)
a b c
代码是:
<?php
// test.php
class AutoController
{
private static function getCommandsArray()
{
$my_dir = array('a', 'b', 'c');
return $my_dir;
}
/**
* The callback which is returning an array with strings, which will be
* auto-completed.
*
* @param $input
* @param $index
* @return array
*/
private static function completionCallback($input, $index)
{
return self::getCommandsArray();
}
/**
* The method which is handling the autocompletion. After it's runned, you can
* autocomplete your commands by hitting the tab-button.
*/
public function actionCompl()
{
readline_completion_function(array('self', 'completionCallback'));
$command_input = readline("Custom command: ");
passthru('echo ' . $command_input);
}
}
$a = new AutoController();
$a->actionCompl();
正如c9s所建议的那样,可以通过扩展bash的自动补全功能而不是使用PHP来获得这种功能。
因此,如果你看一下CLIFramework的自动补全函数,你会看到:
BashGenerator.php
ZshGenerator.php
readline_completion_function()
才能正常工作。当你的脚本没有运行时,按Tab键只是在请求CLI自动完成功能,而不是你的PHP脚本。感谢你澄清了这一点! - Kalle是的!你可以通过PHP实现这个功能!
CLIFramework提供了一个命令来生成你的命令定义所需的bash自动补全脚本。
你也可以在PHP中定义你的参数自动补全,生成的bash/zsh自动补全将在运行时返回PHP的执行结果:
https://github.com/c9s/CLIFramework
屏幕录像(bash):
屏幕录像(zsh):