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:

<?php

require_once 'Console/CommandLine.php';
require_once 
'Console/CommandLine/Action.php';

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

// then we can register our action
Console_CommandLine::registerAction('Range''ActionRange');

// 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

    Поддержать сайт на родительском проекте КГБ