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 GET and POST parameters, Console_CommandLine accepts three types of parameter names:

So in our example, one can call

  • web.php?-f=d.m.Y

  • web.php?--format=d.m.Y

  • web.php?format=d.m.Y

For 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 h1 tags.

  • 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());
}
?>
    Поддержать сайт на родительском проекте КГБ