# 模块核心控制器

您可以为模块建立一个核心控制器文件,在该文件内,您可以准备好模块的安装、卸载、更新、启用、禁用事件方法,在用户对本模块执行对应操作时,系统将自动执行对应的方法。

# 核心控制器文件名

  • 核心控制器是以模块标识名进行首字母大写的方式来命名的
模块唯一标识 核心控制器文件名 类名
test Test Test
userlogin Userlogin Userlogin
login1 Login1 Login1

# 核心控制器方法

<?php

namespace modules\test;

use think\facade\Db;
use app\common\library\Menu;
use app\admin\model\MenuRule;

class Test
{
    /**
     * 安装模块时执行的方法
     */
    public function install()
    {
        // 往后台常规管理内添加一个菜单
        $pMenu = MenuRule::where('name', 'routine')->value('id');
        $menu  = [
            [
                'type'      => 'menu',
                'title'     => '通知公告管理',
                'name'      => 'routine/notice',
                'path'      => 'routine/notice',
                'icon'      => 'el-icon-ChatLineRound',
                'menu_type' => 'tab',
                'component' => '/src/views/backend/routine/notice/index.vue',
                'keepalive' => '1',
                'pid'       => $pMenu ? $pMenu : 0,
                'children'  => [
                    ['type' => 'button', 'title' => '查看', 'name' => 'routine/notice/index'],
                    ['type' => 'button', 'title' => '添加', 'name' => 'routine/notice/add'],
                    ['type' => 'button', 'title' => '编辑', 'name' => 'routine/notice/edit'],
                    ['type' => 'button', 'title' => '删除', 'name' => 'routine/notice/del'],
                    ['type' => 'button', 'title' => '快速排序', 'name' => 'routine/notice/sortable'],
                ],
            ]
        ];
        Menu::create($menu);
        
    }

    /**
     * 卸载模块时执行的方法
     */
    public function uninstall()
    {
        // 删除添加的菜单
        Menu::delete('routine/notice', true);
    }
    
    /**
     * 启用模块时执行的方法
     */
    public function enable()
    {
        // 修改系统配置
        Db::name('config')
            ->where('name', 'record_number')
            ->update([
                'value' => '备案号-测试1',
            ]);

        // 启用模块添加的菜单
        Menu::enable('routine/notice');

        // 假设模块添加了单独的配置菜单,下面这行代码可以添加一个:系统配置 -> 快速配置入口
        Config::addQuickEntrance('测试模块配置', '/admin/test/config');

        // 如果模块的配置信息没有保存于数据库,可以利用缓存备份配置,避免模块更新时配置数据丢失
        $config = Cache::pull('test-module-config');
        if ($config) {
            @file_put_contents(config_path() . 'test.php', $config);
        }
    }

    /**
     * 禁用模块时执行的方法
     */
    public function disable()
    {
        // 禁用模块添加的菜单
        Menu::disable('routine/notice');

        // 删除系统配置 -> 快速配置入口
        Config::removeQuickEntrance('测试模块配置');

        // 如果模块的配置信息没有保存于数据库,可以利用缓存备份配置,避免模块更新时配置数据丢失
        $config = @file_get_contents(config_path() . 'test.php');
        if ($config) {
            Cache::set('test-module-config', $config, 3600);
        }
    }

    /**
     * 升级模块时执行的方法
     */
    public function update()
    {
        
    }
}