Run CakePHP console from a component
Run the cake console from a CakePHP component. You can also add a task, parameters and send to a background process.
Installation
Create app/controllers/components/shell.php and paste the below code into the file.
Download source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
<?php
/**
* Shell Component
*
* Run cakephp shell scripts
*
* Depending on your operating system check the background process append and prepend variables.
* This script works fine on Ubuntu 8.x - it won't work on Windows unless changed to do so.
*
* @version 0.1 beta
* @author Darren Moore, zeeneo@gmail.com
* @link http://www.zeen.co.uk
*/
class ShellComponent extends Object
{
/**
* Controller
*
* @var object
* @access public
*/
public $controller = null;
/**
* Cake console
*
* @var string
* @access public
*/
public $cakeConsole = null;
/**
* Where php is
*
* @var string
* @access public
*/
public $php = '/usr/bin/php';
/**
* Startup controller
*
* @param object $controller Controller instance
* @access public
* @return void
*/
public function startup(&$controller)
{
$this->controller = $controller;
$this->cakeConsole = ROOT.DS.'cake'.DS.'console'.DS.'cake.php';
}
/**
* Run shell command
*
* Example:
* $this->Shell->run('myshell',array('task'=>'crawler','bg'=>true,'params'=>array('feedId'=>123,'batchId'=>345)));
*
* Options
* - 'task' - Task to run
* - 'params' - Params to pass to shell
* - 'bg' - If script should run in background
*
* @param string $shell Shell command
* @param array $options Options
* @access public
* @return string
*/
public function run($shell,$options = array())
{
//Build command
$cmd = array($shell);
$append = '';
$prepend = '';
//Task
if(isset($options['task']) && !empty($options['task'])) { $cmd[] = $options['task']; }
//Params
if(isset($options['params']) && !empty($options['params']))
{
foreach($options['params'] as $key => $val)
{
$cmd[] = '-'.$key.' '.$val;
}
}
//Background
if(isset($options['bg']) && $options['bg'] == true)
{
$prepend = 'nohup ';
$append = ' > /dev/null &';
}
$cmd = $prepend.$this->php.' '.$this->cakeConsole.' '.implode(' ',$cmd).$append;
return exec($cmd);
}
}
?>
|