Writing a php command line based app using Console_CommandLine

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

About rp

Architect for large, highly scalable LAMP applications and Technical Manager with special focus on metrics based continuous improvement of teams and products. Rajat has close to a decade of experience of a very wide range of skills related to infrastructure, middleware, app servers all the way to front-end technologies and software development methodologies including agile, iterative waterfall, waterfall as well as ah-hoc startup using the right approach in the right context to reduce time to market.