在Yii2控制台命令中输入用户输入

时间:2017-07-22 05:19:27

标签: php yii2

我想在Yii2中创建一个控制台命令,我可以从用户那里获取输入。

我在这里查看了Yii2文档 -

http://www.yiiframework.com/doc-2.0/guide-tutorial-console.html

但我找不到任何有用的东西。

我也在谷歌和StackOverflow上搜索没有运气。

3 个答案:

答案 0 :(得分:1)

查看yii \ helpers \ BaseConsole辅助类方法input()。

input('Enter your name');

会提示你输入你的名字。

或者您可以定义操作方法的参数,以将值传递给操作。

static function actionDoSomething (arg1, arg2, ...);

答案 1 :(得分:1)

任何用户字符串的CLI命令提示符:

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

或只要求确认[是|否]:

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")
      }
      ...
   }
}

答案 2 :(得分:0)

您可以使用prompt()中提供的方法yii\console\Controller,该方法调用yii\helpers\BaseConsole::prompt(),并在用户输入后也提供了附加控件来验证输入,也可以仅根据需要将其标记为它不是空的

$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;
        },
    ]
);
相关问题