自定指令
第一步 创建自定义指令
php think make:command Hello hello
完成后 将在app目录下生成command/Hello.php 文件
会生成一个app\command\Hello命令行指令类,我们修改内容如下:
<?php
declare (strict_types = 1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class Hello extends Command
{
protected function configure()
{
// 指令配置
$this->setName('hello')
->addArgument('name' , Argument::OPTIONAL , '你的城市名称')
->addOption('city' , 'abc' , Option::VALUE_NONE )
->setDescription('the hello command');
}
protected function execute(Input $input, Output $output)
{
$name = trim($input->getArgument('name'));
$name = $name ?: 'thinkphp';
if ($input->hasOption('city')) {
$city = PHP_EOL . 'From ' . $input->getOption('city');
} else {
$city = '';
}
$output->writeln("Hello," . $name . '!' . $city);
}
}
第二步,配置config/console.php文件
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
// 指令定义
'commands' => [
'hello' => 'app\command\Hello',
],
];
此时我们使用命令查询
php think
就会发现:
命令行中 多了 hello 命令
第四步,运行hello命令
php think hello
就会返回
hello
函数执行方法
setName 设置名称
$this->setName(string) // 设置一个指令名称
addOption 添加选项
use think\\console\\input\\Option;
// 无需传值
Option::VALUE_NONE = 1;
// 必须传值
Option::VALUE_REQUIRED = 2;
// 可选传值
Option::VALUE_OPTIONAL = 4;
// 传数组值
Option::VALUE_IS_ARRAY = 8;
$this->setName('hello')
-> ->addOption('city' , 'abc' , Option::VALUE_REQUIRED , '我是一段描述文字' , 'Qinhuangdao') //添加选项
php think hello Qinhuangdao
[root@myLiunx demo.turing.net]# php think hello Qinhuangdao
Hello,Qinhuangdao!
[root@myLiunx demo.turing.net]#
如果我们访问 – city
php think hello Beijing --city
[root@myLiunx demo.turing.net]# php think hello Qinhuangdao --city
Hello,Qinhuangdao!
From 1
[root@myLiunx demo.turing.net]#
execute 参数详解
ask 创建一个类似是否同意或接受的命令
if( $output->ask($input , '我要起飞你是否同意?' , 'yes' ))
{
$output->write('允许起飞');die;
}
confirm 同上 只是多了一个yes/no
if($output->confirm($input , '请求起飞' ))
{
$output->write('飞了');
}
choice 多级选择
if($output->choice($input , '123123' , ['a'=>'yes' , 'b'=>'yess'] , 'yes'))
{
dump($output);die;
}
提示类
$output->write('write');
$output->info('info');
$output->warning('warnig');
$output->error('error');
应用场景
我们可以使用命令创建一个清除数据库的命令 也可以利用系统函数去通过自定义命令操作