Skip to content

自定义指令

指令概述

自定义命令在根目录配置文件config下console.php中添加

php
return [
    // 指令定义
    'commands' => [
          'addon:install' => 'app\command\Addon\Install',
    ],
];

目录app\command\下定义命令实现类,比如插件安装指令

php
class Install extends Command
{
    protected function configure()
    {
        $this->setName('addon:install')
            ->addArgument('addon', Option::VALUE_REQUIRED)
            ->addOption('step', 's', Option::VALUE_REQUIRED)
            ->setDescription('the addon install command');
    }

    protected function execute(Input $input, Output $output)
    {
        $instance = CoreAddonInstallService::instance($input->getArgument('addon'));
        $step = $input->getOption('step');

        try {
            $instance->$step();
            $output->writeln("Command executed successfully");
        } catch ( Exception $e ) {
            $output->writeln("Command failed " . $e->getMessage());
        }
    }
}

执行创建命令

bash
php think addon:install cms --step install

现有指令

bash
addon:install           #安装插件,支持指定插件名称和安装步骤
addon                   #卸载插件
menu                    #刷新系统菜单或指定插件的菜单
reset                   #重置管理员密码
queue:listen            #启动基于Redis的消息队列,支持消息延迟处理和失败重试
cron:schedule           #定时任务管理器,支持秒级别的定时设置
workerman               #高性能PHP应用容器,集成了计划任务和消息队列功能

自定义指令开发

支持开发者自定义命令行指令,步骤如下:

1.创建指令类,继承think\console\Command

2.在configure方法中设置指令名称、参数和描述

3.在execute方法中实现指令逻辑

4.在项目中注册指令

示例代码框架

php
namespace app\command;

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

class MyCommand extends Command
{
    protected function configure()
    {
        $this->setName('my:command')
            ->setDescription('我的自定义指令');
    }

    protected function execute(Input $input, Output $output)
    {
        // 实现指令逻辑
        $output->writeln('自定义指令执行成功');
    }
}

基于 MIT 协议发布