How to run console command in yii2 from web
It can be done much simpler
$oldApp = \Yii::$app;new \yii\console\Application([ 'id' => 'Command runner', 'basePath' => '@app', 'components' => [ 'db' => $oldApp->db, ],);\Yii::$app->runAction('migrate/up', ['migrationPath' => '@yii/rbac/migrations/', 'interactive' => false]);\Yii:$app = $oldApp;
As of Yii2 - 2.0.11.2 advanced app -- this works
First let's make sure controller and namespace correct. In this case frontend app accessing console application import method()
In console\controllers\FhirController
Set the alias to be available in the console\config\main.php [OPTIONAL]
'aliases' => [ '@common' => dirname(__DIR__), '@frontend' => dirname(dirname(__DIR__)) . '/frontend', '@backend' => dirname(dirname(__DIR__)) . '/backend', '@console' => dirname(dirname(__DIR__)) . '/console',],
Finally from the frontend view, make the call like this:In this case, calling the controller route fhir then method import()
$consoleController = new console\controllers\FhirController('fhir', Yii::$app); $consoleController->runAction('import');
On a site I'm overhauling, I have a need for a background task, that can be toggled via an action, which requires that I can also find its pid using ps. After much googling and almost as much swearing, I pieced together the solution.
# First change to (already-calculated) correct dir:chdir($strPath);# Now execute with nohup, directed to dev/null, and crucially with & at end, to run async:$output = shell_exec("nohup php yii <console controller>/<action> > /dev/null &");
Yes, I understand that shell_exec should be used with extreme caution, thanks.