Home » Console » Console_CommandLine » Manual
Console_CommandLine is a full featured package for managing command line options and arguments highly inspired from the python optparse module, it allows the developer to easily build complex command line interfaces.
Introduction
Introduction – introduction to the Console_CommandLine package
Introduction
Console_CommandLine is a convenient, flexible, and powerful library for parsing command-line options and arguments.
It uses adeclarative style of command-line parsing: you create an instance of Console_CommandLine, populate it with options, arguments and even sub-commands and parse the command line. Console_CommandLine allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.
DISCLAIMER: since Console_CommandLine was highly inspired from the python optparse module and thus is very similar to it, some parts of this document were shamelessly copied from optparse manual.
A simple example:
<?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());
}
?>
With the above lines of code, users of the script can now use the program like this:
$ <yourscript> --file=outfile -q
As it parses the command line, Console_CommandLine sets attributes of the
result object returned by
Console_CommandLine::parse()
method based on user-supplied command-line values.
When
Console_CommandLine::parse()
returns from parsing this command line,
$result->options['filename'] will be
"outfile" and $result->options['quiet']
will be TRUE.
Console_CommandLine supports both long and short options, allows short options to be merged together, and allows options to be associated with their arguments in a variety of ways.
The following lines are all equivalent for the above example:
$ <yourscript> -f outfile --quiet $ <yourscript> --quiet --file outfile $ <yourscript> -q -foutfile $ <yourscript> -qfoutfile
Additionally, to get help, users can do this:
$ <yourscript> -h $ <yourscript> --help
These commands will print:
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
Console_CommandLine also manage the program version automatically:
$ <yourscript> --version
The above command will print:
$ <yourscript> version 1.5.0.
where the value of yourscript is determined at runtime (normally from
$argv[0], except if you specified explicitely a
name for your parser).
Creating the parser
Creating the parser – how to create a parser using PHP code or an XML definition file
Console_CommandLine constructor
Console_CommandLine::__construct() takes an optional array of parameters explained in the table below. Note that if you are using an XML definition file, you can pass these parameters in it (see XML example for details).
| name | type | required | description |
|---|---|---|---|
| name | string | no, default to $argv[0] if not given |
the name of your program |
| description | string | no, but recommended for the help message | the description of your program: this should explain what your program is supposed to do |
| version | mixed (string or numeric) | no, note that if not given, the --version option will not be available | the program version number |
| add_help_option | boolean | no, default to TRUE | if set to FALSE the parser will not generate automatically the "help" option |
| add_version_option | boolean | no, default to TRUE | if set to FALSE the parser will not generate automatically the "version" option |
| force_posix | boolean | no, default to FALSE | if set to TRUE, the parser will force POSIX compliance (please see the gettext manual for more information) |
Using PHP code
The examples below demonstrate how to instanciate Console_CommandLine and build a parser using PHP code.
The simplest way
<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine(array(
'description' => 'A useful description for your program.',
'version' => '0.0.1', // the version of your program
));
?>
Alternative method
<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->description = 'A useful description for your program.';
$parser->version = '0.0.1'; // the version of your program
?>
Using an XML definition file
The examples below demonstrate how to instanciate Console_CommandLine and build a parser using an XML definition file, this can be very useful if you have a big program or if you need to reuse your user interface settings for a web frontend for example.
The XML file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<command>
<description>A useful description for your program.</description>
<version>0.0.1</version>
</command>
The PHP file
<?php
require_once 'Console/CommandLine.php';
$parser = Console_CommandLine::fromXmlFile('example.xml');
?>
Using an XML string you would have called Console_CommandLine::fromXmlString() instead of Console_CommandLine::fromXmlFile() of course.
Managing command line options
Managing command line options – how to add options to the parser and use them.
Some background
Options are used to provide extra information to tune or customize the execution of a program. In case it wasn't clear, options are usually optional. A program should be able to run just fine with no options whatsoever. Pick a random program from the Unix or GNU toolsets. Can it run without any options at all and still make sense? The main exceptions are find, tar, and dd--all of which are mutant oddballs that have been rightly criticized for their non-standard syntax and confusing interfaces.
Lots of people want their programs to have "required options". Think about it. If it's required, then it's not optional! If there is a piece of information that your program absolutely requires in order to run successfully, that's what arguments are for.
As an example of good command-line interface design, consider the humble cp utility, for copying files. It doesn't make much sense to try to copy files without supplying a destination and at least one source. Hence, cp fails if you run it with no arguments. However, it has a flexible, useful syntax that does not require any options at all:
$ cp SOURCE DEST $ cp SOURCE ... DEST-DIR
You can get pretty far with just that. Most cp implementations provide a bunch of options to tweak exactly how the files are copied: you can preserve mode and modification time, avoid following symlinks, ask before clobbering existing files, etc. But none of this distracts from the core mission of cp, which is to copy either one file to another, or several files to another directory.
Adding options with Console_CommandLine
To add options to your parser, just create the parser as explained in the previous section and use the Console_CommandLine::addOption() method.
The Console_CommandLine::addOption() method takes two arguments:
-
the option name: a string that will be used to access the
option in the result object. For example if you name your option
foo, you will access to the result object like this:
$result->options['foo']; - the options parameters: an array of various informations, as explained below.
| name | type | required | description | example |
|---|---|---|---|---|
| short_name | string | yes, if no long_name given | the option short name | -o |
| long_name | string | yes, if no short_name given | the option long name | --orientation |
| description | string | no, but recommended for the help message | a description for the option | orientation of the page: ltr (default) or rtl |
| action | string | no, default to "StoreString" | the option action (see next section for details) | StoreString |
| default | mixed | no | the option default value | ltr |
| choices | array | no, only relevant for options that expect argument(s) | list of possible values for the option | array('ltr', 'rtl') |
| list | array | no, only relevant for options that use the "List" action | list of values to display | array('blue', 'green', 'yellow') |
| add_list_option | boolean | no, default to FALSE | this property is only relevant when the choices property is set, if set to TRUE the parser will generate an additional option to list the choices (eg. --list-foo). | TRUE |
| help_name | string | no, if not given it will default to the option name | the name to display in the option help line | page_orientation (the help ligne will be: --orientation=page_orientation) |
Adding commandline options
<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine(array(
'description' => 'A useful description for your program.',
'version' => '0.0.1', // the version of your program
));
// Adding a simple option that takes no argument and that tell our program to
// turn on verbose output:
$parser->addOption(
'verbose',
array(
'short_name' => '-v',
'long_name' => '--verbose',
'description' => 'turn on verbose output',
'action' => 'StoreTrue'
)
);
// Adding an option that will store a string
$parser->addOption(
'orientation',
array(
'short_name' => '-o',
'long_name' => '--orientation',
'description' => 'orientation of the page, "ltr" (default) or "rtl"',
'action' => 'StoreString',
'default' => 'ltr',
'help_name' => 'page_orientation'
)
);
try {
$result = $parser->parse();
print_r($result->options);
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
Now if the user type:
$ <yourprogram> -vo rtl
or (equivalent):
$ <yourprogram> --verbose --orientation=rtl
The output of the above script will be:
Array ( [verbose] => 1 [orientation] => rtl [help] => [version] => )
Options actions
Actions tell the parser how to handle option values, among other things they tell the parser if the option expects a value or not and how to store this value in the result object.
StoreTrue
This action tells the parser to store the value true in the result object if the option is present in the command line, for example:
$ <yourprogram> -v
will store TRUE in $result->options['verbose'],
assuming the option was defined like this:
<?php
$parser->addOption('verbose', array('short_name'=>'-v', 'action'=>'StoreTrue'));
$result = $parser->parse();
?>
StoreFalse
This action tells the parser to store the value false in the result object if the option is present in the command line, for example:
$ <yourprogram> -q
will store FALSE in $result->options['verbose'],
assuming the option was defined like this:
<?php
$parser->addOption('verbose', array('short_name'=>'-q', 'action'=>'StoreFalse'));
$result = $parser->parse();
?>
StoreString
This action tells the parser that the option expects a value and to store this value as a string in the result object, for example:
$ <yourprogram> -o out.txt
will store the string "out.txt" in
$result->options['outfile'],
assuming the option was defined like this:
<?php
$parser->addOption('outfile', array('short_name'=>'-o', 'action'=>'StoreString'));
$result = $parser->parse();
?>
StoreInt
This action tells the parser that the option expects a value and to store this value as an integer in the result object, for example:
$ <yourprogram> --width=500
will store the integer 500 in $result->options['width'],
assuming the option was defined like this:
<?php
$parser->addOption('width', array('long_name'=>'--width', 'action'=>'StoreInt'));
$result = $parser->parse();
?>
StoreFloat
This action tells the parser that the option expects a value and to store this value as a float in the result object, for example:
$ <yourprogram> -l=0.3
will store the float 0.3 in $result->options['level'],
assuming the option was defined like this:
<?php
$parser->addOption('level', array('short_name'=>'-l', 'action'=>'StoreFloat'));
$result = $parser->parse();
?>
Counter
This action tells the parser to increment the value in the result object each time it encounters the option in the command line, for example:
$ <yourprogram> -vvvv
or the equivalent:
$ <yourprogram> -v -v -v --verbose
will store the integer 4 in
$result->options['verbose_level'],
assuming the option was defined like this:
<?php
$parser->addOption('verbose_level', array(
'short_name' => '-v',
'long_name' => '--verbose',
'action' => 'Counter'
));
$result = $parser->parse();
?>
Help
This action tells the parser to display the help message if it encounters the option in the command line, most of the time you won't need this since it is handled by Console_CommandLine internally.
Version
This action tells the parser to display the program version if it encounters the option in the command line, as for Help action, chances are that you won't need this since it is handled by Console_CommandLine internally.
Password
This action allows the user to either type the password on the commandline or to be prompted for it (will not echo on unix systems), some examples:
<?php
$parser->addOption('password', array('short_name'=>'-p', 'action'=>'Password'));
$result = $parser->parse();
?>
$ <yourprogram> -ps3cret
will store the string "s3ecret" in
$result->options['password']
whereas:
$ <yourprogram> -p
will "prompt" the user for entering his/her password
without echoing it, and will store "s3ecret" in
$result->options['password']
Callback
This action allows to specify a PHP callback to handle user input. The callback must be a php callable and must accept five arguments:
- the value of the option;
- the Console_CommandLine_Option_Callback instance
- the Console_CommandLine_Result instance
- the Console_CommandLine instance (the parser)
- an array of additional parameters that you specify when building your option.
Your callback function must return the modified (or not modified) value (the first argument).
All these arguments should give you enough flexibility to build complex callback actions.
If the callback is to a class method, then the method must be declared as a public.
Here is a simple example:
<?php
/**
* A simple encryption callback.
*
*/
function encryptCallback($value, $option, $result, $parser, $params=array())
{
if (!isset($params['salt'])) {
$params['salt'] = '';
}
return sha1($params['salt'] . $value);
}
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->addOption('encrypt', array(
'short_name' => '-e',
'long_name' => '--encrypt',
'action' => 'Callback',
'description' => 'encrypt the given value using sha1 + salt',
'callback' => 'encryptCallback',
'action_params' => array('salt' => 'x2897ZHKx7200j1__2')
));
try {
$result = $parser->parse();
echo $result->options['encrypt'] . "\n";
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
Now if the user type:
$ <yourprogram> -e foobar
The output of the above script will be:
7f12da3b1c126d7a47745b09dc0040c92cee1700
List
a special action that simply output an array as a list.
<?php
$parser->addOption('list_colors', array(
'short_name' => '-l',
'long_name' => '--list-colors',
'action' => 'List',
'action_params' => array(
'list' => array('blue', 'green', 'yellow'),
'delimiter' => ',' //optional
)
));
$result = $parser->parse();
?>
$ <yourprogram> --list-colors
will display the list of colors separated by commas.
Managing command line arguments
Managing command line arguments – how to add arguments to the parser and use them
Some background
Arguments are for those pieces of information that your program absolutely, positively requires to run.
A good user interface should have as few absolute requirements as possible. If your program requires 17 distinct pieces of information in order to run successfully, it doesn't much matter how you get that information from the user, most people will give up and walk away before they successfully run the program. This applies whether the user interface is a command-line, a configuration file, or a GUI: if you make that many demands on your users, most of them will simply give up.
In short, try to minimize the amount of information that users are absolutely required to supply and use sensible defaults whenever possible. Of course, you also want to make your programs reasonably flexible. That's what options are for.
Adding arguments with Console_CommandLine
To add arguments to your parser, just create the parser as explained in the previous section and use the Console_CommandLine::addArgument() method.
The Console_CommandLine::addArgument() method takes two arguments:
-
the argument name: a string that will be used to access the
argument in the result object. For example if you name your
argument foo, you will access to the result object like this:
$result->args['foo']; - the arguments parameters: an array of various informations as explained below.
| name | type | required | description | example |
|---|---|---|---|---|
| description | string | no, but recommended for the help message | a description for the argument | entry list of input files separated by spaces |
| multiple | boolean | no, default to FALSE | tells the parser that the argument expects multiples values | TRUE |
| optional | boolean | no, default to FALSE | tells the parser that the argument is optional | TRUE |
| help_name | string | no, if not given it will default to the argument name | the name to display in the argument help line | files |
Adding commandline arguments
<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
// add an array argument
$parser->addArgument('input_files', array('multiple'=>true));
// add a simple argument
$parser->addArgument('output_file');
try {
$result = $parser->parse();
print_r($result->args);
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
If the user type:
$ <yourprogram> file1 file2 file3
The output of the above script will be:
Array
(
[input_files] => Array
(
[0] => file1
[1] => file2
)
[output_file] => file3
)
Managing command line sub-commands
Managing command line sub-commands – how to add sub-commands to the parser and use them
What are sub-commands ?
Some programs are very complex, you can't do anything about that but you need to provide the best user interface possible in order to have happy users. In some cases, sub-commands can be very useful, take the PEAR installer for example, it is much more clearer to separate the installer functionalities than to mix all functionalities in the same interface, that's why you have an interface like:
$ pear install <options> <pkgname> $ pear upgrade <options> <pkgname> and so on...
Adding sub-commands with Console_CommandLine
Adding sub-commands is quite simple, basically you use the Console_CommandLine::addCommand() method that returns a Console_CommandLine_Command instance and then you build your command instance like you would do for the main parser (add options, arguments etc...). One thing to remember is that sub-commands are exactly the same as main parsers: they have the same properties and methods.
Let's take a simple example to demonstrate the use of sub-commands, in the following code we will build a simple command line program that will have two sub-commands: "foo" and "bar":
<?php
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// create the parser
$parser = new Console_CommandLine(array(
'description' => 'A great program that can foo and bar !',
'version' => '1.0.0'
));
// add a global option to make the program verbose
$parser->addOption('verbose', array(
'short_name' => '-v',
'long_name' => '--verbose',
'action' => 'StoreTrue',
'description' => 'turn on verbose output'
));
// add the foo subcommand
$foo_cmd = $parser->addCommand('foo', array(
'description' => 'output the given string with a foo prefix'
));
$foo_cmd->addOption('reverse', array(
'short_name' => '-r',
'long_name' => '--reverse',
'action' => 'StoreTrue',
'description' => 'reverse the given string before echoing it'
));
$foo_cmd->addArgument('text', array(
'description' => 'the text to output'
));
// add the bar subcommand
$bar_cmd = $parser->addCommand('bar', array(
'description' => 'output the given string with a bar prefix'
));
$bar_cmd->addOption('reverse', array(
'short_name' => '-r',
'long_name' => '--reverse',
'action' => 'StoreTrue',
'description' => 'reverse the given string before echoing it'
));
$bar_cmd->addArgument('text', array(
'description' => 'the text to output'
));
?>Of course, we could also build our parser with sub-commands using an xml file, the xml file would be:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<command>
<description>A great program that can foo and bar !</description>
<version>1.0.0</version>
<option name="verbose">
<short_name>-v</short_name>
<long_name>--verbose</long_name>
<description>turn on verbose output</description>
<action>StoreTrue</action>
</option>
<command>
<name>foo</name>
<description>output the given string with a foo prefix</description>
<option name="reverse">
<short_name>-r</short_name>
<long_name>--reverse</long_name>
<description>reverse the string before echoing it</description>
<action>StoreTrue</action>
</option>
<argument name="text">
<description>the text to output</description>
</argument>
</command>
<command>
<name>bar</name>
<description>output the given string with a bar prefix</description>
<option name="reverse">
<short_name>-r</short_name>
<long_name>--reverse</long_name>
<description>reverse the string before echoing it</description>
<action>StoreTrue</action>
</option>
<argument name="text">
<description>the text to output</description>
</argument>
</command>
</command>
Also note that sub-commands support aliases, for example it is possible to have an "update" command and specify "up" as an alias (shortcut) of the command:
<?php
$parser->addCommand('update', array(
'description' => 'Update the given package',
'aliases' => array('up'), // we can have more than 1 alias
));
?>
So far, so good, now let's see how to use this parser. When a user type a sub-command in the command line, the result object will have two properties set: the Console_CommandLine_Result::$command_name that will contain the name (as a string) of the sub-command typed by the user, and the Console_CommandLine_Result::$command that will contain a Console_CommandLine_Result instance, specific to the provided sub-command. For example with the above parser, we would do:
<?php
try {
$result = $parser->parse();
// find which command was entered
switch ($result->command_name) {
case 'foo':
// the user typed the foo command
// options and arguments for this command are stored in the
// $result->command instance:
print_r($result->command);
exit(0);
case 'bar':
// the user typed the bar command
// options and arguments for this command are stored in the
// $result->command instance:
print_r($result->command);
exit(0);
default:
// no command entered
exit(0);
}
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
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
Using Console_CommandLine in web environments
Using Console_CommandLine in web environments – How to use the same script from your browser
Introduction
So there is a nice shell script that does everything it ever should do, and other people - without shell access - have to use it now. Or the script needs to be called regularly from outside the server it is running on. What now?
If your server runs a HTTP server with PHP, the problem is already solved
because Console_Commandline supports reading HTTP
$_GET and $_POST variables
out of the box.
A simple example
The scripts task in this example is to print out the current time. The user may customize the output by specifying the format string.
Between shell and web access is only one difference: On the web, the text
shall be printed out in large letters by wrapping it in a
h1 tag.
Console_CommandLine by itself cares about reading
HTTP GET and POST variables when it is run through PHP's CGI or web
server (e.g. Apache with mod_php). Let's try it:
<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->description = 'Print out the current time';
$parser->version = '1.23';
$parser->addOption(
'format',
array(
'short_name' => '-f',
'long_name' => '--format',
'action' => 'StoreString',
'default' => 'Y-m-d H:i:s',
'description' => 'date()-compatible format string',
)
);
$result = $parser->parse();
echo date($result->options['format']) . "\n";
?>
Shell output
$ php web.php
2009-06-13 10:10:15
$ php web.php --help
Print out the current time
Usage:
web.php [options]
Options:
-f format, --format=format date()-compatible format string
-h, --help show this help message and exit
-v, --version show the program version and exit
$ php web.php --format=d.m.Y
13.06.2009
Web output without parameters
2009-06-13 10:10:15
Web output for web.php?--help
Print out the current time Usage: --help [options]
Options: -f format, --format=format date()-compatible format string -h,
--help show this help message and exit -v, --version show the program
version and exit
Web output for web.php?format=d.m.Y
13.06.2009
The functionality is there, but it does not look nice.
When using
GETandPOSTparameters, Console_CommandLine accepts three types of parameter names:
short_nameas configured for the optionlong_nameas configured- option name as passed as first parameter to Console_CommandLine::addOption().
So in our example, one can call
web.php?-f=d.m.Yweb.php?--format=d.m.Yweb.php?format=d.m.YFor arguments, the argument name has to be used as GET or POST key.
A prettier example
Building upon our previous example, we care about pretty output here:
-
Time wrapped in
h1tags. - Monospaced help text
- Monospaced error text
While we did not catch any errors - as there are nearly none to produce in that example - the code contains it now for completeness.
First and foremost, we check if we are in an HTTP environment by checking
the SAPI (Server API) name. If we are not in CLI, we echo out
<h1> and </h1>.
To get the help text printed with monospaced text, a custom renderer is defined. For the sake of easiness, the default console renderer is extendet since it does nearly everything we need here.
<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->description = 'Print out the current time';
$parser->version = '1.23';
$parser->addOption(
'format',
array(
'short_name' => '-f',
'long_name' => '--format',
'action' => 'StoreString',
'default' => 'Y-m-d H:i:s',
'description' => 'date()-compatible format string',
)
);
class HtmlRenderer extends Console_CommandLine_Renderer_Default
{
public function usage()
{
return '<pre>' . parent::usage() . '</pre>';
}
public function error($error)
{
return '<pre>' . parent::error($error) . '</pre>';
}
}
$parser->accept(new HtmlRenderer());
$http = (php_sapi_name() != 'cli');
try {
$result = $parser->parse();
if ($http) {
echo '<h1>';
}
echo date($result->options['format']) . "\n";
if ($http) {
echo '</h1>';
}
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
Examples
Examples – various code examples
Basic example
Basic example
<?php
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// create the parser
$parser = new Console_CommandLine(array(
'description' => 'zip given files using the php zip module.',
'version' => '1.0.0'
));
// add an option to make the program verbose
$parser->addOption(
'verbose',
array(
'short_name' => '-v',
'long_name' => '--verbose',
'action' => 'StoreTrue',
'description' => 'turn on verbose output'
)
);
// add an option to delete original files after zipping
$parser->addOption(
'delete',
array(
'short_name' => '-d',
'long_name' => '--delete',
'action' => 'StoreTrue',
'description' => 'delete original files after zip operation'
)
);
// add the files argument, the user can specify one or several files
$parser->addArgument(
'files',
array(
'multiple' => true,
'description' => 'list of files to zip separated by spaces'
)
);
// add the zip file name argument
$parser->addArgument('zipfile', array('description' => 'zip file name'));
// run the parser
try {
$result = $parser->parse();
// write your program here...
print_r($result->options);
print_r($result->args);
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
Basic example using an XML definition file
Basic example (XML file)
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<command>
<description>zip given files using the php zip module.</description>
<version>1.0.0</version>
<option name="verbose">
<short_name>-v</short_name>
<long_name>--verbose</long_name>
<description>turn on verbose output</description>
<action>StoreTrue</action>
</option>
<option name="delete">
<short_name>-d</short_name>
<long_name>--delete</long_name>
<description>delete original files after zip operation</description>
<action>StoreTrue</action>
</option>
<argument name="files">
<description>a list of files to zip together</description>
<multiple>true</multiple>
</argument>
<argument name="zipfile">
<description>path to the zip file to generate</description>
</argument>
</command>
Basic example (PHP file)
<?php
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// create the parser from xml file
$xmlfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ex2.xml';
$parser = Console_CommandLine::fromXmlFile($xmlfile);
// run the parser
try {
$result = $parser->parse();
// todo: your program here ;)
print_r($result->options);
print_r($result->args);
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
Sub-commands example
Sub-commands example
<?php
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// create the parser
$parser = new Console_CommandLine(array(
'description' => 'A great program that can foo and bar !',
'version' => '1.0.0'
));
// add a global option to make the program verbose
$parser->addOption('verbose', array(
'short_name' => '-v',
'long_name' => '--verbose',
'action' => 'StoreTrue',
'description' => 'turn on verbose output'
));
// add the foo subcommand
$foo_cmd = $parser->addCommand('foo', array(
'description' => 'output the given string with a foo prefix'
));
$foo_cmd->addOption('reverse', array(
'short_name' => '-r',
'long_name' => '--reverse',
'action' => 'StoreTrue',
'description' => 'reverse the given string before echoing it'
));
$foo_cmd->addArgument('text', array(
'description' => 'the text to output'
));
// add the bar subcommand
$bar_cmd = $parser->addCommand('bar', array(
'description' => 'output the given string with a bar prefix'
));
$bar_cmd->addOption('reverse', array(
'short_name' => '-r',
'long_name' => '--reverse',
'action' => 'StoreTrue',
'description' => 'reverse the given string before echoing it'
));
$bar_cmd->addArgument('text', array(
'description' => 'the text to output'
));
// run the parser
try {
$result = $parser->parse();
if ($result->command_name) {
$st = $result->command->options['reverse']
? strrev($result->command->args['text'])
: $result->command->args['text'];
if ($result->command_name == 'foo') {
echo "Foo says: $st\n";
} else if ($result->command_name == 'bar') {
echo "Bar says: $st\n";
}
}
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>
Sub-commands example using an XML definition file
Sub-commands example (XML file)
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<command>
<description>A great program that can foo and bar !</description>
<version>1.0.0</version>
<option name="verbose">
<short_name>-v</short_name>
<long_name>--verbose</long_name>
<description>turn on verbose output</description>
<action>StoreTrue</action>
</option>
<command>
<name>foo</name>
<description>output the given string with a foo prefix</description>
<option name="reverse">
<short_name>-r</short_name>
<long_name>--reverse</long_name>
<description>reverse the string before echoing it</description>
<action>StoreTrue</action>
</option>
<argument name="text">
<description>the text to output</description>
</argument>
</command>
<command>
<name>bar</name>
<description>output the given string with a bar prefix</description>
<option name="reverse">
<short_name>-r</short_name>
<long_name>--reverse</long_name>
<description>reverse the string before echoing it</description>
<action>StoreTrue</action>
</option>
<argument name="text">
<description>the text to output</description>
</argument>
</command>
</command>
Sub-commands example (PHP file)
<?php
// Include the Console_CommandLine package.
require_once 'Console/CommandLine.php';
// create the parser
$xmlfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ex4.xml';
$parser = Console_CommandLine::fromXmlFile($xmlfile);
// run the parser
try {
$result = $parser->parse();
if ($result->command_name) {
$st = $result->command->options['reverse']
? strrev($result->command->args['text'])
: $result->command->args['text'];
if ($result->command_name == 'foo') {
echo "Foo says: $st\n";
} else if ($result->command_name == 'bar') {
echo "Bar says: $st\n";
}
}
} catch (Exception $exc) {
$parser->displayError($exc->getMessage());
}
?>