Extending Console_CommandLine

Extending Console_CommandLine – how to customize this package to achieve specific tasks

Adding custom actions

Console_CommandLine allows you to register custom actions when you need it. Basically, you just create a action class that inherits from Console_CommandLine_Action and you call the Console_CommandLine::registerAction() method to register it.

Let's take a simple example, suppose we want to create a "range" action that would allow the user to type:

$ <yourprogram> -r 1,5

And in our Console_CommandLine_Result instance we would have:

// $result->options['range']: array('min' => 1, 'max' => 5)

Here's how we would do:


require_once 'Console/CommandLine.php';

ActionRange extends Console_CommandLine_Action
    public function 
$range explode(','str_replace(' '''$value));
        if (
count($range) != 2) {
            throw new 
'Option "%s" must be 2 integers separated by a comma',
$this->setResult(array('min' => $range[0], 'max' => $range[1]));

// then we can register our action

// and now our action is available !
$parser = new Console_CommandLine();
$parser->addOption('range', array(
'short_name'  => '-r',
'long_name'   => '--range',
'action'      => 'Range'// note our custom action
'description' => 'A range of two integers separated by a comma'
// etc...


Using a custom renderer

TODO: write this section

how to add sub-commands to the parser and use them (Previous) How to use the same script from your browser (Next)
Last updated: Sun, 29 Aug 2010 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report or add a note.
View this page in:

User Notes:

There are no user contributed notes for this page.