Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a console command in web application in Yii 2.0

Tags:

yii2

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 post How to call a console command in web application action in Yii?

Since Yii 2.0 structure is very different from Yii 1.1 ,I get errors if I try to include command/userReportController.php .Can someone guide me on this?

like image 656
user2466573 Avatar asked Aug 18 '14 02:08

user2466573


3 Answers

You should use an extension like https://github.com/vova07/yii2-console-runner-extension

like image 141
zelenin Avatar answered Nov 09 '22 09:11

zelenin


I think this is the simplest solution:

$controller = new YourConsoleController(Yii::$app->controller->id, Yii::$app);
$controller->actionYourConsoleAction();
like image 5
Maik Avatar answered Nov 09 '22 09:11

Maik


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')
);
like image 1
Petr Pánek Avatar answered Nov 09 '22 09:11

Petr Pánek