life quality
life quality

Reputation: 65

Yii2 Call Console controller/action in backend controller

I crited controller

SiteMapController.php

with action

index

in console folder of Yii2
enter image description here
and I can run it from command line.
enter image description here
But I need run it from controller of backend/controllers folder. it means I should run index action of controller SiteMapController.php from Yii2 backend controller action. Here my test code but it not works. Backend/controllers/BlogController.php

private function runSiteMapGenerate(){
    $cr = new ConsoleRunner(['file' => '@console']);
    $cr->run('site-map');
}

I tried both scripts

"vova07/yii2-console-runner-extension": "*",
"tebazil/yii2-console-runner": "^0.0.0"

But its not help to run index

I have no more options.

Upvotes: 0

Views: 2182

Answers (2)

robsch
robsch

Reputation: 9728

If you use vova07/yii2-console-runner-extension you need to set file to the path of the yii script which is usually located in the root folder - you don't specify the console directory here. So it is very likely that you create the object this way:

// assuming you have file 'yii' in the root directory:
$cr = new ConsoleRunner(['file' => '@app/yii']);

Then the actual call should work:

// assuming that 'index' is the default action
$cr->run('site-map');
// or
$cr->run('site-map/index');

Info: if a console command should be executed you actually call yii with some parameters for the command. You don't call the command directly. yii starts a console application. Just have a look into this file. It is part of the yii2-app-advanced (present if the init script was executed on setup) and yii2-app-basic project templates.

Upvotes: 0

Bira
Bira

Reputation: 5506

Find the yii directory using chdir and run the next shell_exec. Using this you can make it simple and no need to install any extensions.

chdir('../yiifolder'); //folder that contains yii
$output = shell_exec('php yii migrate');
var_dump($output);

This is tested on my server.

Output:

string 'Yii Migration Tool (based on Yii v2.0.6)

No new migration found. Your system is up-to-date.
' (length=93)

Upvotes: 2

Related Questions