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

thinkphp5中Command的使用

2023.05.18

893

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');
    }
}

免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

相关新闻

让人头疼的python 编码问题!!!

2018.10.29

0

中文编码问题是用中文的程序员经常头大的问题,在python下也是如此,那么应该怎么理解和解决python的编码问题呢?

让人头疼的python 编码问题!!!

2018.10.29

0

中文编码问题是用中文的程序员经常头大的问题,在python下也是如此,那么应该怎么理解和解决python的编码问题呢?

让人头疼的python 编码问题!!!

2018.10.29

0

中文编码问题是用中文的程序员经常头大的问题,在python下也是如此,那么应该怎么理解和解决python的编码问题呢?