Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Snippets by user Roger Stanton Snippets by user Roger Stanton

simple console options for batch scripts

I was looking for this type of functionality:

'php batch/mybatch.php app=batch env=dev'

The following allows me to use the same batch scripts for different environments and applications. It also keeps batch scripts lean by only requiring one line.

batch/run_me.php:

require_once('lib/batch.php');
 
//
// begin batch scripting here
//

batch/lib/batch.php:

set_time_limit(0);
 
$app = get_app($argv[1]);
$env = get_env($argv[2]);
$debug = get_debug($argv[3]);
 
//
// initialize symfony
//
 
define('SF_ROOT_DIR',         realpath(dirname(__FILE__).'/../..'));
define('SF_APP',              $app);
define('SF_ENVIRONMENT',      $env);
define('SF_DEBUG',            $debug);
 
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
 
sfContext::getInstance();
 
//
// initialize doctrine (just an example)
//
 
$connection = sfDoctrine::connection();
 
//
// parse command line args
//
 
function get_app($argv)
{
  preg_match('@app=(\w+)@', $argv, $match);
 
  return isset($match[1]) ? $match[1] : 'batch';
}
 
function get_env($argv)
{
  preg_match('@env=(\w+)@', $argv, $match);
 
  return isset($match[1]) ? $match[1] : 'dev';
}
 
function get_debug($argv)
{
  preg_match('@(true|false)@', $argv, $match);
 
  return isset($match[1]) ? $match[1] : true;
 
}
by Roger Stanton on 2006-09-25, tagged batch  cli