CLI PHP options using Zend_Console_Getopt

I’m loving the CLI executables right now, making loads of them! Remember you don’t get the memory or time out issues that you do on the web server php.

However I noticed that the regex broke when we had a hyphen separated option name, such as –most-recent for instance. It turns out PHP uses a command called getopt() (unsurprisingly). I was about to start using this when I realised that we can actually use Zend_Console_Getopt() instead!

Building on my previous post, I have changed the script somewhat. Check it out, it’s easy enough to follow!

 

#!/usr/bin/env php
<?php
/* Load Zend Framework or Freak out */
try
{
 require_once(__DIR__.'/../../inc/zend_init.php');
$config = array(
 'help' => ' Display this help',
 'most-recent' => ' Select most recent results',
 'year=i' => ' Select the Year year=[year]',
 'week=i' => ' Select the Week week=[week]',
 );

 $options = new Zend_Console_Getopt($config);
 $options->parse();
}
catch(Exception $e)
{
 die("\n".$e->getMessage());
}

if(!empty($options->year) && !empty($options->week))
{
 try
 {
 // code here
 }
 catch(Exception $e)
 {
 echo "\n** ERROR DETECTED **\n ".$e->getMessage()."\n\n";
 }
}
elseif(!empty($options->{'most-recent'}))
{
 //code here
}
else
{
 die($options->getUsageMessage());
}

Note the curly brackets! This is how you deal with hyphens when using Object notation. Also, in the config, you’ll see year=i. This means it is an integer. You can also have =s, being a string. Check the Zend Framework manual for more details, and have fun!