最近研究了下tp5中command的使用,再次做下小记
下载tp5后,cmd运行think,输入php think,会显示相关的操作命令,如下图
现在我们要创建自己的命令,要怎么做呢
首先,先创建一个类,继承于Command,然后在application\command.php 里面进行注册,此处我在application\index\command\文件夹下创建Test.php文件
<?php
namespace app\index\Command;
use think\console\Command;
use think\console\input;
use think\console\output;
class Test extends Command {
protected function configure()
{
$this->setName('Test')->setDescription('Test');
}
protected function execute(Input $input, Output $output)
{
$this->output->write('Test正在执行任务');
}
}
其中 configure和execute方法时必须的,此处已用了think\console\input 和think\console\output,这个在execute方法中可以用到
然后在application\command.php里面注册我们的命令
<?php
return [
'app\index\command\Test'
];
注册好之后,命令就已经建好了,再次在cmd中输入php think,我们的命令就会显示
输入命令:php think Test
这里就是执行了execute方法,output和input的方法有很多,简单用一下,比如下面这个例子
protected function execute(Input $input, Output $output)
{
$this->output->newLine();
$this->output->info('1 + 1 = ');
$result = $this->output->choice($input,'请选择正确的答案', ['1','2','3']);
if ($result == 2)
{
$this->output->write('恭喜你,回答正确!!!');
}
else
{
$this->output->write('回答错误!!!');
}
}
输入php think Test 运行结果
输入选项 1,回车
这些只是command在cmd中的简单使用,command更多会用在执行计划任务方面,php文件可以这样调用命令:
<?php
namespace app\index\controller;
use think\console;
class Index
{
public function index()
{
//调用Test命令执行
$result = console::call('Test');
}
}
未经允许不得转载:肥猫博客 » thinkphp5中Command的使用