Snippets

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

Navigation

Environment in batch files

Normally, there is a controller for each environment in your app. However, batch scripts have only one controller, and hence you have to set the environment manually.

This code allows you to set the environment to 'dev' while developing, and to 'prod' when your batch script has to run on the production server. The clever thing here is that this is done transparently on the production server (whoever calls your scripts do not have to make a choice of environment).

Create a file batchConfig.php (eg. in config folder):

$env = (((count($argv) >= 2) && ($argv[1] == 'dev')) ? 'dev' : 'prod');
 
define('SF_ROOT_DIR',    realpath(dirname(__file__).'/..'));
define('SF_APP',         'frontend');
define('SF_ENVIRONMENT', $env);
define('SF_DEBUG',       true);
 
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
 
// Initialize database manager.
$databaseManager = new sfDatabaseManager();
$databaseManager->initialize();
 

(The first line does all the work.) In all your batch files, just include it with:

require_once('config/batchConfig.php');
 

and leave out all the usual definitions and database connection code.

In dev, just call:

php myscript.php dev
 

and do as usual in prod:

php myscript.php
 

As an added benefit, your batch files will only contain actual business logic.

by Martin Kock on 2007-10-04, tagged batch 
You need to create an account or log in to post a comment or rate this snippet.