前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >thinkphp5中Command的使用

thinkphp5中Command的使用

作者头像
超级小可爱
发布2023-10-18 15:23:52
5130
发布2023-10-18 15:23:52
举报
文章被收录于专栏:小孟开发笔记小孟开发笔记

最近研究了下tp5中command的使用,再次做下小记

下载tp5后,cmd运行think,输入php think,会显示相关的操作命令,如下图

现在我们要创建自己的命令,要怎么做呢

首先,先创建一个类,继承于Command,然后在application\command.php 里面进行注册,此处我在application\index\command\文件夹下创建Test.php文件

代码语言:javascript
复制
<?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里面注册我们的命令

代码语言:javascript
复制
<?php
 
return [
    'app\index\command\Test'
];

注册好之后,命令就已经建好了,再次在cmd中输入php think,我们的命令就会显示

输入命令:php think Test

这里就是执行了execute方法,output和input的方法有很多,简单用一下,比如下面这个例子

代码语言:javascript
复制
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文件可以这样调用命令:

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

未经允许不得转载:肥猫博客 » thinkphp5中Command的使用

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档