\documentclass{article}
\usepackage{ulem}
\usepackage{graphicx}
\usepackage{hyperref}
\pagestyle{headings}
\begin{document}
\part{Horde\_Argv}
\textit{Horde\_Argv} is a library for parsing command line arguments with various actions, providing help, grouping options, and more. It is ported from Python's Optik (<a href="http://optik.sourceforge.net/\">http://optik.sourceforge.net/\textbackslash\{\}</a>).

\section{Basic Usage}
While \textit{Horde\_Argv} is quite flexible and powerful, you don't have to jump through hoops or read reams of documentation to get started. This document aims to demonstrate some simple usage patterns that will get you started using \textit{Horde\_Argv} in your scripts.

To parse a command line with \textit{Horde\_Argv}, you must create an \texttt{Horde\_Argv\_Parser} instance and define some options. You'll have to import the \texttt{Horde\_Argv\_Parser} classes in any script that uses \textit{Horde\_Argv}, but it is suggested that you use an autoloader instead:

<pre><code class="language-php">
require\_once 'Horde/Autoloader/Default.php';
</code></pre>
Early on in the main program, create a parser:

<pre><code class="language-php">
\$parser = new Horde\_Argv\_Parser();
</code></pre>
Then you can start defining options. The basic syntax is:

<pre><code class="language-php">
\$parser->addOption('opt\_str', ..., array('attr' => 'value', ...));
</code></pre>
That is, each option has one or more option strings, such as "-f" or "--file", and several option attributes that tell \textit{Horde\_Argv} what to expect and what to do when it encounters that option on the command line.

Typically, each option will have one short option string and one long option string, e.g.:

<pre><code class="language-php">
\$parser->addOption('-f', '--file', ...);
</code></pre>
You're free to define as many short option strings and as many long option strings as you like, as long as there is at least one option string overall.

Once all of your options are defined, instruct \textit{Horde\_Argv} to parse your program's command line:

<pre><code class="language-php">
list(\$values, \$args) = \$parser->parseArgs();
</code></pre>
(You can pass an argument list to \texttt{parseArgs()} if you like, but that's rarely necessary: by default it uses \$\_SERVER['argv'].)

\texttt{parseArgs()} returns two values:

\begin{itemize}
\item \$values is a \texttt{Horde\_Argv\_Values} object containing values for all of your options -- e.g. if "--file" takes a single string argument, then \$values->file (or \$values['file']) will be the filename supplied by the user, or NULL if the user did not supply that option.


\item \$args is the list of arguments left over after parsing options.


\end{itemize}
This tutorial document only covers the four most important option attributes: "action", "type", "dest" (destination), and "help". Of these, "action" is the most fundamental.

\subsection{Option actions}
Actions tell \textit{Horde\_Argv} what to do when it encounters an option on the command line. There is a fixed set of actions hard-coded into \textit{Horde\_Argv}; adding new actions is an advanced topic covered in <a href="https://wiki.horde.org/Doc/Dev/HordeArgvExtend">Extending Horde\_Argv</a>. Most actions tell \textit{Horde\_Argv} to store a value in some variable -- for example, take a string from the command line and store it in an attribute of options.

If you don't specify an option action, \textit{Horde\_Argv} defaults to "store".

\subsubsection{The store action}
The most common option action is store, which tells \textit{Horde\_Argv} to take the next argument (or the remainder of the current argument), ensure that it is of the correct type, and store it to your chosen destination.

For example:

<pre><code class="language-php">
\$parser->addOption(
    '-f', '--file',
    array('action' => 'store', 'type' => 'string', 'dest' => 'filename')
);
</code></pre>
Now let's make up a fake command line and ask \textit{Horde\_Argv} to parse it:

<pre><code class="language-php">
\$args = array('-f', 'foo.txt');
list(\$values, \$args) = \$parser->parseArgs(args);
</code></pre>
When \textit{Horde\_Argv} sees the "-f", it consumes the next argument, "foo.txt", and stores it in \$values->filename, where values is the first return value from \texttt{parseArgs()}. So, after this call to \texttt{parseArgs()}, \texttt{\$values->filename} is "foo.txt".

Some other option types supported by \textit{Horde\_Argv} are "int" and "float". Here's an option that expects an integer argument:

<pre><code class="language-php">
\$parser->addOption('-n', array('type' => 'int', 'dest' => 'num'));
</code></pre>
Note that I didn't supply a long option, which is perfectly acceptable. I also didn't specify the action, since the default is "store".

Let's parse another fake command-line. This time, we'll jam the option argument right up against the option -- "-n42" (one argument) is equivalent to "-n 42" (two arguments).

<pre><code class="language-php">
list(\$values, \$args) = \$parser->parseArgs(array('-n42'));
echo \$values->num;
</code></pre>
will print "42".

Trying out the "float" type is left as an exercise for the reader.

If you don't specify a type, \textit{Horde\_Argv} assumes "string". Combined with the fact that the default action is "store", that means our first example can be a lot shorter:

<pre><code class="language-php">
\$parser->addOption('-f', '--file', array('dest' => 'filename'))
</code></pre>
If you don't supply a destination, \textit{Horde\_Argv} figures out a sensible default from the option strings: if the first long option string is "--foo-bar", then the default destination is "foo\_bar". If there are no long option strings, \textit{Horde\_Argv} looks at the first short option: the default destination for "-f" is "f".

Adding types is covered in "Extending \textit{Horde\_Argv}".

\subsubsection{Handling flag (boolean) options}
Flag options -- set a variable to TRUE or FALSE when a particular option is seen -- are quite common. \textit{Horde\_Argv} supports them with two separate actions, "store\_true" and "store\_false". For example, you might have a verbose flag that is turned on with "-v" and off with "-q":

<pre><code class="language-php">
\$parser->addOption('-v', array('action' => 'store\_true', 'dest' => 'verbose'));
\$parser->addOption('-q', array('action' => 'store\_false', 'dest' => 'verbose'));
</code></pre>
Here we have two different options with the same destination, which is perfectly OK. (It just means you have to be a bit careful when setting default values -- see Default values, below.)

When \textit{Horde\_Argv} sees "-v" on the command line, it sets the verbose attribute of the special "option values" object to a TRUE value; when it sees "-q", it sets verbose to a FALSE value.

\subsubsection{Other actions}
Some other actions supported by \textit{Horde\_Argv} are:

\textbf{"store\_const"}: store a constant value<br />
\textbf{"append"}: append this option's argument to a list<br />
\textbf{"count"}: increment a counter by one<br />
\textbf{"callback"}: call a specified function

These are covered in the <a href="https://wiki.horde.org/Doc/Dev/HordeArgvAdvanced">Advanced Usage</a> and <a href="https://wiki.horde.org/Doc/Dev/HordeArgvCallbacks">Option Callbacks</a> documents.

\subsection{Default values}
All of the above examples involve setting some variable (the "destination") when certain command-line options are seen. What happens if those options are never seen? Since we didn't supply any defaults, they are all set to NULL. Usually, this is just fine, but sometimes you want more control. To address that need, \textit{Horde\_Argv} lets you supply a default value for each destination, which is assigned before the command-line is parsed.

First, consider the verbose/quiet example. If we want \textit{Horde\_Argv} to set verbose to TRUE unless "-q" is seen, then we can do this:

<pre><code class="language-php">
\$parser->addOption('-v', array('action' => 'store\_true', 'dest' => 'verbose', 'default' => true));
\$parser->addOption('-q', array('action' => 'store\_false', 'dest' => 'verbose'));
</code></pre>
Oddly enough, this is exactly equivalent:

<pre><code class="language-php">
\$parser->addOption('-v', array('action' => 'store\_true', 'dest' => 'verbose'));
\$parser->addOption('-q', array('action' => 'store\_false', 'dest' => 'verbose', 'default' => true));
</code></pre>
Those are equivalent because you're supplying a default value for the option's destination, and these two options happen to have the same destination (the verbose variable).

Consider this:

<pre><code class="language-php">
\$parser->addOption('-v', array('action' => 'store\_true', 'dest' => 'verbose', 'default' => false));
\$parser->addOption('-q', array('action' => 'store\_false', 'dest' => 'verbose', 'default' => true));
</code></pre>
Again, the default value for verbose will be TRUE: the last default value supplied for any particular destination attribute is the one that counts.

A clearer way to specify default values is the \texttt{setDefaults()} method of \texttt{Horde\_Argv\_Parser}, which you can call at any time before calling \texttt{parseArgs()}:

<pre><code class="language-php">
\$parser->setDefaults(array('verbose' => true));
\$parser->addOption(...);
list(\$values, \$args) = \$parser->parseArgs();
</code></pre>
As before, the last value specified for a given option destination is the one that counts. For clarity, try to use one method or the other of setting default values, not both.

\subsection{Generating help}
There is one more feature that you will use in every script: \textit{Horde\_Argv}'s ability to generate help messages. All you have to do is supply a help value for each option. Let's create a new parser and populate it with user-friendly (documented) options:

<pre><code class="language-php">
\$usage = 'usage: \%prog [options] arg1 arg2';
\$parser = new Horde\_Argv\_Parser(array('usage' => \$usage));
\$parser->addOption(
    '-v', '--verbose',
    array('action' => 'store\_true', 'dest' => 'verbose', 'default' => 1,
          'help' => 'make lots of noise [default]')
);
\$parser->addOption(
    '-q', '--quiet',
    array('action' => 'store\_false', 'dest' => 'verbose', 
          'help' => 'be vewwy quiet (I'm hunting wabbits)')
);
\$parser->addOption(
    '-f', '--filename',
    array('metavar' => 'FILE', 'help' => 'write output to FILE')
);
\$parser->addOption(
    '-m', '--mode',
    array('default' => 'intermediate',
          'help' => 'interaction mode: one of "novice", "intermediate" [default], "expert"')
);
</code></pre>
If \textit{Horde\_Argv} encounters either '-h' or '--help' on the command-line, or if you just call \texttt{\$parser->printHelp()}, it prints the following to stdout:

<pre><code>
usage: <yourscript> [options] arg1 arg2

options:
  -h, --help           show this help message and exit
  -v, --verbose        make lots of noise [default]
  -q, --quiet          be vewwy quiet (I'm hunting wabbits)
  -fFILE, --filename=FILE
                       write output to FILE
  -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
                       [default], 'expert'
</code></pre>
There's a lot going on here to help \textit{Horde\_Argv} generate the best possible help message:

\begin{itemize}
\item the script defines its own usage message:


\end{itemize}
\begin{quote}
\texttt{\$usage = 'usage: \%prog [options](options) arg1 arg2';}<br />
\textit{Horde\_Argv} expands "\%prog" in the usage string to the name of the current script, i.e. basename(\$\_SERVER['argv'][0]). The expanded string is then printed before the detailed option help.<br />
If you don't supply a usage string, \textit{Horde\_Argv} uses a bland but sensible default: "usage: \%prog <a href="https://wiki.horde.org/options">options</a>", which is fine if your script doesn't take any positional arguments.


\end{quote}
\begin{itemize}
\item every option defines a help string, and doesn't worry about line-wrapping -- \textit{Horde\_Argv} takes care of wrapping lines and making the help output look good.


\item options that take a value indicate this fact in their automatically-generated help message, e.g. for the "mode" option:


\end{itemize}
\begin{quote}
\texttt{-mMODE, --mode=MODE}<br />
Here, "MODE" is called the meta-variable: it stands for the argument that the user is expected to supply to -m/--mode. By default, \textit{Horde\_Argv} converts the destination variable name to uppercase and uses that for the meta-variable. Sometimes, that's not what you want -- for example, the --filename option explicitly sets \$metavar = "FILE", resulting in this automatically-generated option description:<br />
\texttt{-fFILE, --filename=FILE}<br />
This is important for more than just saving space, though: the manually written help text uses the meta-variable "FILE", to clue the user in that there's a connection between the formal syntax "-fFILE" and the informal semantic description "write output to FILE". This is a simple but effective way to make your help text a lot clearer and more useful for end users.


\end{quote}
\subsection{Print a version number}
Similar to the brief usage string, \textit{Horde\_Argv} can also print a version string for your program. You have to supply the string, as the version argument to \texttt{Horde\_Argv\_Parser}:

<pre><code class="language-php">
\$parser = new Horde\_Argv\_Parser(array('usage' => '\%prog [-f] [-q]', 'version' => '\%prog 1.0'));
</code></pre>
Note that "\%prog" is expanded just like it is in usage. Apart from that, version can contain anything you like. When you supply it, \textit{Horde\_Argv} automatically adds a "--version" option to your parser. If it encounters this option on the command line, it expands your version string (by replacing "\%prog"), prints it to stdout, and exits.

For example, if your script is called "/usr/bin/foo", a user might do:

<pre><code class="language-shell">
\$ /usr/bin/foo --version
foo 1.0
</code></pre>
\subsection{Error-handling}
The one thing you need to know for basic usage is how \textit{Horde\_Argv} behaves when it encounters an error on the command-line -- e.g. "-n4x" where the "-n" option takes an integer. \textit{Horde\_Argv} prints your usage message to stderr, followed by a useful and human-readable error message. Then it terminates with a non-zero exit status by calling \texttt{exit()}.

If you don't like this, subclass \texttt{Horde\_Argv\_Parser} and override the \texttt{parserError()} method. See Extending \textit{Horde\_Argv}.

\subsection{Putting it all together}
Here's what a \textit{Horde\_Argv}-based scripts usually look like:

<pre><code class="language-php">
require\_once 'Horde/Autoloader/Default.php';

[...]

\$usage = 'usage: \%prog [options] arg';
\$parser = new Horde\_Argv\_Parser(array('usage' => \$usage));
\$parser->addOption(
    '-f', '--file',
    array('type' => 'string', 'dest' => 'filename',
          'help' => 'read data from FILENAME')
);
\$parser->addOption(
    '-v', '--verbose',
    array('action' => 'store\_true', 'dest' => 'verbose')
);
\$parser->addOption(
    '-q', '--quiet',
    array('action' => 'store\_false', 'dest' => 'verbose')
);
[... more options ...]

list(\$values, \$args) = \$parser->parseArgs();
if (count(\$args) != 1) \{
    \$parser->parserError('incorrect number of arguments');
\}

if (\$values->verbose) \{
    printf('reading \%s...\%n', \$values->filename);
\}

[... go to work ...]
</code></pre>
\end{document}
