I have a PHP command line script which kicks off a job to a job server, with the job name being an argument. The job names are namespaced, such as Foo:Bar_Baz_JobName. Is there a way I could implement auto-completion, like how typing the first few letters of a filename and pressing tab bash completes the file name for you. I know it can be done, because tab-completion works on ubuntu with apt-get, I just don't know if it can be done in PHP.
Autocompletion is done using the GNU readline library, which apparently is accessible from PHP. Specifically, look at readline_completion_function
. Usage is fairly simple; you call readline_completion_function
with one argument, a callback function that handles the completion. The callback function takes the first few letters (basically, whatever you type before pressing TAB) as input and should return an array of possible matches.
I would say that considering the type of interaction you are looking for (apt-get autocomplete) this method is not good.
In fact before to get a autocomplete function you have to run the script and then you'll access the autocomplete function.
The autocomplete function is partial. So, it like the bash autocomplete not the zsh.
In the shell:
➜ ~ php test.php (enter)
Custom command: (tab)
a b c
Custom command: (tab)
a b c
The code is:
<?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();
As suggested by c9s it is possible to obtain this kind of functionality but extending
autocomplete functionality of your bash, not with PHP.
So, if you see the autocomplete function of CLIFramework for example you'll see:
BashGenerator.php
ZshGenerator.php
Which is used to generate the bash script to extends the bash or zsh autocomplete.
So, it depends on the shell you are using the way you have to make the autocomplete.
Some references:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With