![]() |
|
Snippets |
|
I create a script to use complex arguments while runing script from command line.
It also allow to switch SF_ENVIRONMENT, SF_APP and SF_DEBUG directly from command line.
Just create configBatch.php in your project's config directory and paste this :
<?php define('SF_ROOT_DIR', realpath(dirname(__file__).'/..')); $argv = array(); for ($i = 1; $i < $_SERVER["argc"]; $i++) { if ($_SERVER["argv"][$i]{0} === '-') { // argument $value = ( isset($_SERVER["argv"][$i+1]) && $_SERVER["argv"][$i+1]{0} !== '-' ? $_SERVER["argv"][$i+1] : true ); if ($_SERVER["argv"][$i]{1} === '-') { // long argument $argv[substr($_SERVER["argv"][$i], 2)] = $value; } else { foreach (str_split($_SERVER["argv"][$i]) as $arg) { if (ereg('[a-zA-Z0-9]', $arg)) { $last_arg = $arg; $argv[$arg] = true; } } $argv[$last_arg] = $value; } } } define('SF_APP', (isset($argv['app'])?$argv['app']:'www')); define('SF_ENVIRONMENT', (isset($argv['env'])?$argv['env']:'prod')); define('SF_DEBUG', (isset($argv['debug'])?1:0)); require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
Then, start your batch file with :
<?php require_once(realpath(dirname(__file__).'/..').DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'configBatch.php'); // Your script start here
Now, you can pass arguments to you script :
php -f /path/to/project/batch/my_batch.php -rf some_value --help --foo bar
Here is the generated $argv :
$argv = array ( 'r' => true, 'f' => 'some_value', 'help' => true, 'foo' => 'bar', );
You can also change the SF_ENVIRONMENT with the --env argument, the SF_APP with the --app argument and the debug flag with --debug argumnent
Enjoy