Yii2 console控制台
在console 地下创建控制器
<?php
namespace console\controllers;
use yii\console\Controller;
use yii\console\ExitCode ;
use yii\helpers\Console;
class HelloController extends Controller
{
public $message;
public function options($actionID)
{
return ['message'];
}
public function optionAliases()
{
return ['m' => 'message']; //别名
}
public function actionIndex()
{
echo $this->message;
}
// 命令 "yii example/create test" 会调用 "actionCreate('test')"
public function actionCreate($name) { }
// 命令 "yii example/index city" 会调用 "actionIndex('city', 'name')"
// 命令 "yii example/index city id" 会调用 "actionIndex('city', 'id')"
// 命令 "yii example/add test" 会调用 "actionAdd(['test'])"
// 命令 "yii example/add test1,test2" 会调用 "actionAdd(['test1', 'test2'])"
public function actionAdd(array $name) { }
}
?>
有趣的要来了控制输出的字体颜色
引入use yii\helpers\Console;
Console::output("HELLO");
输出 hello
Console::ansiFormat("要输出的内容",[颜色....]);
字体颜色有
FG_BLACK
FG_RED
FG_GREEN
FG_YELLOW
FG_BLUE
FG_PURPLE
FG_CYAN
FG_GREY
背景颜色
BG_BLACK
BG_RED
BG_GREEN
BG_YELLOW
BG_BLUE
BG_PURPLE
BG_CYAN
BG_GREY
如何输出一个 字体蓝色 背景黄色
$test = Console::ansiFormat("Hello",[Console::FG_BLUE,Console::BG_YELLOW]);
Console::output("{$test}");
获取用户输入的
$test = Console::input("请输入- : ");
Console::output("{$test}");
判断用户输入 yes 还是no
$test = Console::confirm("yes or no ? ");
Console::output("{$test}");
让用户选择
$test = Console::select("select ? ",['1'=>'跑步','2'=>'游泳','3'=>'滑板']);
Console::output("{$test}");
进度条
Console::startProgress(0, 100,[Console::FG_BLACK]);
for ($n = 1; $n <= 100; $n++) {
usleep(2000);
Console::updateProgress($n, 100);
}
Console::endProgress();
对输入的数据验证
$test = Console::prompt("Like for Phper",['required'=>true,'error'=>'必须输入']);
Console::output("{$test}");
required 真假,是否必须填写
default 默认值
pattern 正则匹配
validator 自定义验证函数
error 错误信息