创建自定义命令行:
1.首先是注册cammand:
application/cammand:
2.创建类,继承Cammand:
namespace app\common\command;usethink\console\Command;class Chat extendsCommand
{protected functionconfigure()
{$this->setName('chat')->setDescription('Here is the remark ');
}protected function execute(Input $input, Output $output)
{$output->writeln("TestCommand:");
}
}
下面说一下参数的含义
首先configure 和execute这两个是必须存在的.
configure是配置信息:
其中setName 标识的php think 后面紧跟的命令名
自定义命令行还支持传递参数和可选选项
php think chat start --restart
其中start为参数,必须要输入的,在configure中配置为:
->addArgument('number1')
执行的是时候调用execute里面的
$input->getArgument('number1') 获取用户输入的参数,
setDescription: 这个是执行php think list 展示的简述,类似的还有
->setHelp("这个是使用--help时展示的信息");
getArgument()方法是有默认值的,不止一个参数,下面是tp的框架代码
/**
* 添加参数
* @param string $name 名称
* @param int $mode 类型,
* @param string $description 描述
* @param mixed $default 默认值
* @return Command*/
public function addArgument($name, $mode = null, $description = '', $default = null)
{$this->definition->addArgument(new Argument($name, $mode, $description, $default));return $this;
}
其中$mode:
参数类型: self::REQUIRED 或者 self::OPTIONAL
required常量值为1,
optional 常量值2
他们标识的是是否必须
示例:
->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload", 'start')
其中action 作为execute获取参数的键, Argument::OPTIONAL是$mode的值,表示非必填项,第三个是提示描述,最后一个是默认值,默认传递的start
下面是可以选选项的使用
在configure方法里:
->addOption('restart')
在执行execute里通过
if($input->hasOption('restart')){
//执行里面的里面的逻辑
}
同理下面是tp框架的代码:
/**
* 添加选项
* @param string $name 选项名称
* @param string $shortcut 别名
* @param int $mode 类型
* @param string $description 描述
* @param mixed $default 默认值
* @return Command*/
public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
{$this->definition->addOption(new Option($name, $shortcut, $mode, $description, $default));return $this;
}
示例:
->addOption('daemon', 'd', Option::VALUE_NONE, '该进程已后台运行')
daemon 是execute获取options时的键,d,是别名
同理$mode标识的是是否必须,
第三个参数是描述
第四个是默认值,
只有第一个是必须的参数,其他均为可选,跟addArguments一致.
在命令行输出数据:
下面是一些可以使用颜色的输出
//红色背景上的白字
$output->writeln('white text on a red background');//绿字
$output->writeln('green text');//黄字
$output->writeln('yellow text');//黄色色背景上的黑字
$output->writeln('black text on a yellow background');//青色背景上的黑字
$output->writeln('black text on a cyan background');//红背景上的白字
$output->writeln('white text on a red background');//支持混合输出
$output->writeln('green textblack text on a cyan background......');
通过控制器去触发命令行操作
//调用命令行的指令
$output = Console::call('app:demo', ['--num', '10', 'kitty']);
tp命令行还可以做一些简单的判断
//execute方法内
$question = $output->confirm($input, '是否继续操作?', false);if (!$question) {return;
}