【ThinkPHP】TP6动态切换数据库
作者: thtomatic 分类: php笔记 评论: [ 0 ] 条 浏览: [ 83 ] 次
因业务需要在插件中链接一个第三方的数据库,为了不让用户修改配置文件,所以只能根据代码来写入数据库配置文件,在model中进行切换
实现业务逻辑代码如下
此方式的第二步 有BUG 请移步至《【ThinkPHP】TP6动态切换数据库 修改版》 查看修改后的版本
1.根据客户输入的数据库信息 写入新php文件
public function editConfigApi() { $data = $this->request->post(['type','hostname','hostport','username','password','database','prefix','tag_id','domain']); $configFilePath = $this->addon_path.'config.php'; $file = fopen($configFilePath,'w+'); $writeData = [ 'connections'=>[ 'kodbox'=>$data, ] ]; if(false !== $file) { fwrite($file,''); $res = fwrite($file,$this->spliceArray($writeData)); fclose($file); } } protected function spliceArray($array) { return '<?php'."\n".'return '."\n".var_export($array,true).';'; }
2.在model层进行切换 (此方案有BUG,已废弃)
class BaseModel extends Model { use SoftDelete; public $listField = '*'; public $listOrder = 'id desc'; public $listAppend = []; public function __construct(array $data = []) { $kodConfigFile = App::getRootPath(). 'addons'.DIRECTORY_SEPARATOR.'kodbox2album'.DIRECTORY_SEPARATOR.'config.php'; Config::load($kodConfigFile,'database'); $this->connection = 'kodbox'; parent::__construct($data); }
版权所有:《thtomatic》 => 《【ThinkPHP】TP6动态切换数据库》
本文地址:https://ask.mykeji.net/phpnotes/267.html
除非注明,文章均为 《简单记录》 原创,欢迎转载!转载请注明本文地址,谢谢。
发表评论: