Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 console command pass arguments with name

Tags:

yii2

I want to use commands as

php yii sync anyvar2=anValue  anyVar1=anyValue

In controller

 public function actionIndex(){
       echo $anyVar1;
       echo $anyVar2;
   }

I tried with php yii sync [--anyvar2=anValue ,--anyVar1=anyValue]

like image 859
Yasar Arafath Avatar asked Jan 02 '17 12:01

Yasar Arafath


2 Answers

1) If you want to set controller parameters:

class SyncController extends \yii\console\Controller
{
    public $anyVar1;
    public $anyVar2;

    public function options($actionID)
    {
        return array_merge(parent::options($actionID), [
            'anyVar1', 'anyVar2'
        ]);
    }
}

Now you can set them like that:

php yii sync --anyVar1=aaa --anyVar2=bbb

2) If you want to just pass variables as arguments:

public function actionIndex($anyVar1, $anyVar2)
{
    // ...
}

Now you can set them like that:

php yii sync aaa bbb
like image 96
Bizley Avatar answered Oct 31 '22 22:10

Bizley


Got solution

when need to pass variable in console

  1. Variable should declared in public scope.

  2. Variable should returned in options function

    Ex:

    class SyncController extends \yii\console\Controller
     {
      public $anyVar1;
      public $anyVar2;
    
    public function options()
    {
      return ['anyVar1','anyVar2'];
    }
    public function actionIndex(){
    
      echo $this->anyVar1."\n";
      echo $this->anyVar2."\n";
    }
    }
    

    In console

php yii sync --anyVar2=1111 --anyVar1=999

like image 24
Yasar Arafath Avatar answered Nov 01 '22 00:11

Yasar Arafath