I have a console command to generate user report. I want to call the same from my web application. I am using Yii 2.0.0 beta version.I tried to follow answers given in this
use this code:
$application = new yii\console\Application($config);
$application->runAction('controller/action');
I'm using this method instead of yii
console command, because I'm running Yii on managed VPS where unix commands are not supported in cron, only php scripts.
To run it this way instead of console, the yii configuration must be initialized first, of course:
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/common/config/bootstrap.php');
require(__DIR__ . '/console/config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/common/config/main.php'),
require(__DIR__ . '/common/config/main-local.php'),
require(__DIR__ . '/console/config/main.php'),
require(__DIR__ . '/console/config/main-local.php')
);
If you really want to run Console controller by Web controller likes migrate:
public function actionMigrate()
{
// Keep current application
$oldApp = \Yii::$app;
// Load Console Application config
$config = require \Yii::getAlias('@app'). '/config/console.php';
new \yii\console\Application($config);
$result = \Yii::$app->runAction('migrate', ['migrationPath' => '@app/migrations/', 'interactive' => false]);
// Revert application
\Yii::$app = $oldApp;
return;
}
Above sample code is for yii2-app-basic
template, you could change path for yii2-app-advanced
template.
You should use an extension like https://github.com/vova07/yii2-console-runner-extension
yii2-console-runner-extension keeps loading.
Try this:
It's yii (without ext, not yii.bat)
Make sure that php folder added to PATH variable (Windows)
$op = shell_exec ( 'absolute/path/to/yii ' . 'cache/flush-all' );
\yii\helpers\VarDumper::dump($op, 10, 1);
Output:
The following cache components were processed:
* cache (yii\\caching\\FileCache)
I think this is the simplest solution:
$controller = new YourConsoleController(Yii::$app->controller->id, Yii::$app);
$controller->actionYourConsoleAction();