ThinkPHP6中使用command自定义命令

近几年FastAdmin框架用的比较多,它是基于ThinkPHP5的一个框架,在其中使用command,也就是自定义命令非常方便。

最近接手一个项目用到了ThinkPHP6框架,需要使用command来处理一些比较耗时的任务,但原代码里并没有使用,那就自己来创建吧。

  1. app目录下新建command目录,并在其下新建一个文件,比如Test.php,内容如下
<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * Test
 */
class Test extends Command
{
    /**
     * 命令配置
     */

    protected function configure()
    {
        $this->setName('Test')->setDescription('Test');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return int|null|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function execute(Input $input, Output $output)
    {
        echo "completed \n";
    }
}
  1. 注册命令,编辑config\console.php,内容如下:
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
    // 指令定义
    'commands' => [
        'WordTrim' => '\app\command\Test',
    ],
];
  1. 通过命令行使用这个命令
php think Test

如果输出completed就说明命令执行成功了!

Leave a Comment

豫ICP备19001387号-1