如何为某个应用配置独立数据库?

分享 未结 精帖
0 630
苟哥
苟哥 2023-04-14 09:03

如果我们想为某个应用单独配置数据库,可以如下操作(举例为微信平台(wechat)应用单独配置数据库):

1、编辑wechat/config/thinkorm.php

<?php

$system_config = config('thinkorm');

$default = $system_config['connections'][$system_config['default']];
$hostname = '链接地址';
$hostport = '端口';
$database = '数据库名称';
$username = '数据库账户';
$password = '数据库密码';
$charset = '编码';
$prefix = '表前缀';

$system_config['connections']['wechat'] = [
    // 数据库类型
    'type' => 'mysql',
    // 服务器地址
    'hostname' => $hostname,
    // 数据库名
    'database' => $database,
    // 数据库用户名
    'username' => $username,
    // 数据库密码
    'password' => $password,
    // 数据库连接端口
    'hostport' => $hostport,
    // 数据库连接参数
    'params' => [],
    // 数据库编码默认采用utf8
    'charset' => $charset,
    // 数据库表前缀
    'prefix' => $prefix,
    // 断线重连
    'break_reconnect' => true,
    // 关闭SQL监听日志
    'trigger_sql' => false,
    // 开启自动写入时间戳字段
    'auto_timestamp' => true,
];

return $system_config;


2、在应用的配置目录(wechat/config)下新增bootstrap.php:

<?php


return [
    plugin\wechat\app\bootstrap\ThinkOrm::class
];


3、新建文件夹wechat/app/bootstrap,并在文件夹下创建类文件 ThinkOrm.php:

<?php 

namespace plugin\wechat\app\bootstrap;


use Throwable;
use Webman\Bootstrap;
use Workerman\Timer;
use think\Paginator;
use think\facade\Db;
use think\db\connector\Mysql;

class ThinkOrm implements Bootstrap
{
    // 进程启动时调用
    public static function start($worker)
    {
        $config = config('plugin.wechat.thinkorm');
        $default = $config['default'] ?? false;
        $connections = $config['connections'] ?? [];
        // 配置
        Db::setConfig($config);
        // 维持mysql心跳
        if ($worker) {
            Timer::add(55, function () use ($connections, $default) {
                if (!class_exists(Mysql::class, false)) {
                    return;
                }
                foreach ($connections as $key => $item) {
                    if ($item['type'] == 'mysql') {
                        try {
                            if ($key == $default) {
                                Db::query('select 1');
                            } else {
                                Db::connect($key)->query('select 1');
                            }
                        } catch (Throwable $e) {}
                    }
                }
                Db::getDbLog(true);
            });
        }
        Paginator::currentPageResolver(function ($pageName = 'page') {
            $page = request()->input($pageName, 1);
            if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int)$page >= 1) {
                return (int)$page;
            }
            return 1;
        });
    }
}


4、修改应用的模型类$connection属性,为了修改方便我们习惯为每个应用也建立个模型基类,然后只要修改基类中的属性即可。修改wechat/app/model/Base.php:

// 设置当前模型的数据库连接
protected $connection = 'wechat';


收藏
回帖
  • 消灭零回复