PHP Option Parser (optparser2) 03 Jun, 2005
[I] Don’t like wastin’ time for music
That won’t make me proud.— Ben Folds
At the office, we’ve started doing a lot more things from the console, and to that end, we’ve developed some scripts writen in (of course) PHP to simplify some of our more repetitive tasks. Yes, I know PHP is a hammer, but work with me here, at least it’s not PERL.
Several of these scripts needed to accept commandline
arguments, which PHP conveniently places in $_SERVER['argv']
for us, but doesn’t help with mapping that array into anything
a bit more useful, like named flags or whatnot. I ended up
using a lot of if (in_array("-h", $_SERVER['argv']))...
but once I went to all that trouble of checking for flags, I
didn’t know where genuine arguments such as files or numbers
were, and certainly couldn’t show a warning if a flag was
used that had no effect.
Then I read about inamidst’s argparse (written in Python) and decided that something similar would really be a boon to the the scripts I was working on.
Since PHP is a somewhat agile language, I went ahead and
wrote the tests first, which made it very easy to tell when
it was “done,” but also helped me figure out the syntax I was
going to use for specifying options. There’s also a demo
included, although the tests do document the behavior, they
are a little convoluted if you’re just trying to figure out
how in the world it’s simpler to use optparser2
rather than
in_array
.
Source, test suite, and demo available at lab/lib/trunk/optparser2/
Or via anonymous svn to svn://svn.timhatch.com/lab/lib/trunk/optparser2
In order to run the test suite, you’ll also need to grab
lab/lib/trunk/tests/
. This directory is not required for
normal operation — it’s for developers to make sure changes
don’t break core functionality.
Released under the BSD license.