Petra Barus
Petra Barus

Reputation: 4013

How to determine the location of Yii2 console bootstrap file in the runtime?

I'm creating a plugin that has a console controller.

Here's the plugin layout

plugin/
   controller/
      MyController

The content of the controller itself is something like below

namespace plugin\controller;

class MyController extends \yii\console\Controller {
     public function actionFoo(){
     }
     public function actionBar(){
     }
}

The config of an app that uses that controller will look like this

'controllerMap' => [
    'my' => [
        'class' => 'plugin\controller\MyController'
    ]
]

That way the app can use something like this for executing the controller

yii my/foo

The problem is, in the actionFoo I want to execute the actionBar through exec().

This is as far as I can go,

Since I can set the name of the console command for the controller using the controller map, I can also pass the name as the attribute of the controller.

'controllerMap' => [
    'my' => [
        'class' => 'plugin\controller\MyController',
        'name' => 'my',
    ]
]

And the controller will be like this

namespace plugin\controller;

class MyController extends \yii\console\Controller {

     public $name = 'my';
     public function actionFoo() {
         $yiipath = 'yii';
         $command = PHP_BINARY . " {$yiipath} {$this->my}/bar";
         exec($command);
     }
     public function actionBar() {
     }
}

The question is, how do I determine the path of the yii script (i.e. Yii console bootstrap file) for the $yiipath variable above?

UPDATE

The only way I can think of is

$yiipath = getcwd()) . DIRECTORY_SEPARATOR . $_SERVER['argv'][0];

but it's kind of dirty. I'm wondering if there's a cleaner or "Yii2" way?

Upvotes: 0

Views: 237

Answers (1)

Evgeniy Tkachenko
Evgeniy Tkachenko

Reputation: 1737

U can add to your yii.php file:

define('YII_EXEC', pathinfo(__FILE__, PATHINFO_EXTENSION));

and use in your controller

$command = "PHP_BINARY YII_EXEC {$this->my}/bar";

Upvotes: 1

Related Questions