Take user input in Yii2 console command

Viewed 3003
3 Answers

CLI command prompt for any user string:

class CronController extends yii\console\Controller
{
   public function actionSendTestmail()
   {
      $emailTo = \yii\helpers\BaseConsole::input("Recipient email: ");
      ...
   }
}

or just ask for confirmation [yes|no]:

class CronController extends yii\console\Controller
{
   public function actionSendTestmail()
   {
      $emailTo = Yii::$app->params["email.to"];
      if(!$this->confirm("Send email to {$emailTo}?")){
         exit("Sending email interrupted.\n")
      }
      ...
   }
}

You can use the method prompt() provided in the yii\console\Controller that calls the yii\helpers\BaseConsole::prompt() and gives you additional control to validate the input too after the user enters or just mark it as required so that it is not empty

$code = $this->prompt(
    'Enter 4-Chars-Pin',
    [
        'required' => true,
        'validator' => function ($input, &$error) {
            if (strlen($input) !== 4) {
                $error = 'The Pin must be exactly 4 chars!';
                return false;
            }
            return true;
        },
    ]
);
Related