创建一个自定义命令类文件,新建application/common/command/Hello.php
<?php
namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
class Hello extends Command
{
/**
* 定义该命令的基本信息
*/
protected function configure()
{
//这个文件定义了一个叫hello的命令,并设置了一个name参数和一个city选项。
$this->setName('hello')
//添加参数
->addArgument('name', Argument::OPTIONAL, "your name")
//添加选项
->addOption('city', null, Option::VALUE_REQUIRED, 'city name')
//设置描述
->setDescription('Say Hello');
}
/**
* 执行的PHP代码逻辑
* @param Input $input 输入数据对象
* @param Output $output 输出数据对象
* @return int|void|null
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
protected function execute(Input $input, Output $output)
{
//获取输入对象的参数
$name = trim($input->getArgument('name'));
//为空判断
$name = $name ?: 'thinkphp';
//检查是否存在选项city
if ($input->hasOption('city')) {//存在则打印相关信息
$city = PHP_EOL . 'From ' . $input->getOption('city');
} else {
$city = '';
}
//往数据库插入一条数据
// Db::table('fa_student')
// ->insert([
// 'name' => '小明' . date("Y-m-d H:i:s", time()),
// 'age' => mt_rand(10, 80),
// ]);
//使用输出对象打印信息在控制台
$output->writeln("Hello," . $name . '!' . $city);
//再查询出数据 并展示在控制台
$list = Db::table('fa_student')
->select();
echo '<pre>';
var_export($list);
die;
}
}
配置application/command.php 文件 追加一个?
app\common\command\Hello
<?php
return [
'app\admin\command\Crud',
'app\admin\command\Menu',
'app\admin\command\Install',
'app\admin\command\Min',
'app\admin\command\Addon',
'app\admin\command\Api',
'app\common\command\Hello',
];
运行hello 命令
php think hello
?输出

?添加命令参数
php think hello xiaobai
?输出

添加ci ty 选项
php think hello xiaobai --city kunming
输出

|