Code snippets for symfony 1.x

Navigation

Interactive shell task for symfony 1.2

This task depends on pear PHP_Shell.

lib/task/shellTask.class.php:

class shellTask extends sfBaseTask
{
  protected function configure()
  {
    $this->addArguments(array(
       new sfCommandArgument('application', sfCommandArgument::OPTIONAL, 'The application name'),
    ));
 
    $this->addOptions(array(
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel'),
      // add your own options here
    ));
 
    $this->namespace        = '';
    $this->name             = 'shell';
    $this->briefDescription = 'Run interactive shell.';
    $this->detailedDescription = <<<EOF
The [shell|INFO] runs interactive shell with symfony enviroment.
Call it with:
 
  [php symfony shell [application]|INFO]
 
Using [application|INFO] argument is recommended. Propel behaviors do not work without application.

EOF;
  }
 
  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
 
    require_once('PHP/Shell.php');
    $__shell = new PHP_Shell();
 
    $f = <<<EOF
Symfony-Shell - Version %s%s
 
>> use '?' to open the inline help
 
EOF;
 
    printf($f, $__shell->getVersion(), $__shell->hasReadline() ? ', with readline() support' : '');
    unset($f);
 
    while($__shell->input()) {
      try {
        if ($__shell->parse() == 0) {
          ## we have a full command, execute it
          $__shell_retval = eval($__shell->getCode());
          foreach(array_keys(get_defined_vars()) as $__shell_var_name) {
            if(substr($__shell_var_name, 0, 7) != '__shell') {
              $GLOBALS[$__shell_var_name] = $$__shell_var_name;
            }
          }
          unset($__shell_var_name);
          if (isset($__shell_retval)) {
            $GLOBALS['_'] = $__shell_retval;
          }
          unset($__shell_retval);
          $__shell->resetCode();
        }
      } catch(Exception $__shell_exception) {
        print $__shell_exception->getMessage();
        $__shell->resetCode();
        unset($__shell_exception);
      }
    }
 
  }
}
 

Usage:

symfony shell [application]

Based on Andrei Baragan's interactive shell for 1.0 and 1.1.

by Marek on 2009-04-09, tagged interactive  shell 

Comments on this snippet

gravatar icon
#1 Marek on 2009-04-09 at 04:49

I forgot to mention that return value of last statement is accessible in $_ variable.