您所在的位置:首页 / 知识分享

thinkphp5中Command的使用

2023.05.18

779

ytj

thinkphp5中Command的使用

<?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('回答错误!!!');
        }
	}


这些只是command在cmd中的简单使用,command更多会用在执行计划任务方面,php文件可以这样调用命令:

<?php
namespace app\index\controller;
 
use  think\console;
class Index
{
    public function index()
    {
        //调用Test命令执行
        $result = console::call('Test');
    }
}

相关新闻

写好 JS 条件语句的 5 条守则

2019.01.08

2580

在用 JavaScript 工作时,我们经常和条件语句打交道,这里有5条让你写出更好/干净的条件语句的建议。

权限系统设计方案

2020.02.25

1725

权限管理是所有后台系统的都会涉及的一个重要组成部分,主要目的是对不同的人访问资源进行权限的控制,避免因权限控制缺失或操作不当引发的风险问题,如操作错误,隐私数据泄露等问题。

AIGC案例实战!如何用AI为可视化大屏设计提效?

2023.04.13

1079

随着 AI 的大火,大家都在考虑如何通过 AI 提升工作效率,接下来简述一下我在可视化领域使用 AI - Midjourney 进行设计提效的尝试。