clip – Command Line Argument Parsing in PHP
Using PHP on the command line can be fun. As much as PHP is geared towards coding for the web, there are a few tools built into the language that make system programming possible.
One of those tools is the global $argv array. PHP initialises this array for us whenever we call our scripts from the command line. However, unless you’re working with a very basic set of arguments, the $argv array stops being useful fast.
For example, suppose we want to write a Mad Libs game in PHP. We allow the user to enter some combination of a noun, a verb, an adjective and a girl’s name and then return a funny sentence which incorporates them all.
Let us also suppose that we’re writing the application on the command line, and that the player will enter the words as arguments for our game.
Now, in PHP, we may quickly decide that we’re going to accept the arguments in an order we pre-define. So, the player might enter something like this:
$ php madlibs.php basketball jump sloppy Mary
And that’s all well and good. But, without remembering the exact order of the arguments, or how many there are, our game becomes hard to use and not very fun.
Besides that, it goes against the expected pattern for command-line arguments (at least in the *nix world, anyway).
Far better would it be if our arguments could be given in any order and even possibly allowing some of the arguments to be optional. This would make our game much more accessible to the newcomer. For example:
$ php madlibs.php --name=Mary --noun=basketball \
--adjective=sloppy --verb=jump
Or even:
$ php madlibs.php -n basketball -N Mary -v jump -a sloppy
Enter ‘clip’!
clip is a simple helper class that aims to speed-up command line development in PHP, taking the arguments collected in $argv and putting them together in a more organised way.
clip turns something like this:
$ php madlibs.php -n "Eifel Tower" -v splat -a smelly -N Jack
… or this:
Array
(
[1] => -n
[2] => Eifel Tower
[3] => -v
[4] => splats
[5] => -a
[6] => smelly
[7] => -N
[8] => Jack
)
… into this:
Array
(
[noun] => Eifel Tower
[verb] => splats
[adjective] => smelly
[name] => Jack
)
It’s light (around 9kb) and hopefully easy to understand. For some examples of how it’s used, check out clip on github.
Make sure you check out the Wiki section, where I’ve provided a simple example of extending the ‘clip’ class to write a basic Mad Libs game.