I am currently writing a PHP app which had to have a command line interface. I came across this excellent library in PEAR Console_CommandLine. Its core functionality is very useful out of the box and in case you need to do something really fancy, there is nothing stopping you from extending it further.
Here is a quick example for anyone interested in getting up and running with it.
<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->description = 'A fantastic command line program that does nothing.';
$parser->version = '1.5.0';
$parser->addOption('filename', array(
'short_name' => '-f',
'long_name' => '--file',
'description' => 'write report to FILE',
'help_name' => 'FILE',
'action' => 'StoreString'
));
$parser->addOption('quiet', array(
'short_name' => '-q',
'long_name' => '--quiet',
'description' => "don't print status messages to stdout",
'action' => 'StoreTrue'
));
try {
$result = $parser->parse();
// do something with the result object
print_r($result->options);
print_r($result->args);
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
gives the output for yourscript -help
A fantastic command line program that does nothing. Usage: tmp.php [options] Options: -f FILE, --file=FILE write report to FILE -q, --quiet don't print status messages to stdout -h, --help show this help message and exit --version show the program version and exit
Details for options/configuration: http://pear.php.net/manual/en/package.console.console-commandline.options.php
Details for command line arguments: http://pear.php.net/manual/en/package.console.console-commandline.arguments.php
Details for extending lib: http://pear.php.net/manual/en/package.console.console-commandline.extending.php
