为了账号安全,请及时绑定邮箱和手机立即绑定

php单例模式数据库类多次链接数据库该如何优化?

php单例模式数据库类多次链接数据库该如何优化?

PHP
呼唤远方 2019-03-09 04:20:19
我写了一个mysql数据库操作类,然后对应每个表都写了一个model类,这些model都继承mysql数据库操作类。我的mysql数据库操作类是单例类形式的。昨天调试代码的时候追踪了一下运行流程,发现每个model文件运行的时候都会走一遍完整的mysql connect selectdb这些基础性的工作,这完全出乎我的意料,我希望达到的目标是像 connect selectdb 这种操作只运行一次,其他的每个model实例化的时候都只初始化 tablename 等一些变量,但是代码改了半天没改对,希望大神们帮忙看看,下面贴代码: Mysql操作类部分代码: public static function getInstance($db = 'master1', array $config = []) { $config += Yaf_Registry::get('config')->database['config'][$db]->toArray(); static $_instance = []; empty($config['model']) && $config['model'] = get_called_class(); $key = md5(implode(',', $config)); if (empty($_instance[$key])) { $instance = $_instance[$key] = new static($config); return $instance; } return $_instance[$key]; } private function __construct(array &$config) { $this->_initConfig($config); $this->_initConnection(); $this->_initTable($config); $this->release(); } private function _initConfig(array &$config) { !empty($config['host']) && $this->_config['host'] = $config['host']; !empty($config['user']) && $this->_config['user'] = $config['user']; !empty($config['pass']) && $this->_config['pass'] = $config['pass']; !empty($config['data']) && $this->_config['data'] = $config['data']; !empty($config['port']) && $this->_config['port'] = $config['port']; !empty($config['char']) && $this->_config['char'] = $config['char']; !empty($config['pref']) && $this->_config['pref'] = $config['pref']; in_array($config['dbug'], [0, 1]) && $this->_config['dbug'] = $config['dbug']; in_array($config['dlog'], [0, 1]) && $this->_config['dlog'] = $config['dlog']; } private function _initConnection() { $this->_conn = mysqli_connect( $this->_config['host'], $this->_config['user'], $this->_config['pass'], $this->_config['data'], $this->_config['port'] ) or die('connect db fail(' . mysqli_connect_errno() . ')' . mysqli_connect_error()); mysqli_query($this->_conn, "set names " . $this->_config['char']); } model 文件代码示例: class Db_UserModel extends MySql {......} 问题是每个model文件实例化时候都是通过 getInstance,例如: Db_UserModel::getInstance() 有多少个model被实例化,就会产生多少次数据库链接。 求教如何改成我希望的那样呢?谢谢了。
查看完整描述

3 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

static $_instance = null;
if ($_instance == null) {
    $_instance = new static($config);
}
return $_instance;
查看完整回答
反对 回复 2019-03-18
?
不负相思意

TA贡献1777条经验 获得超10个赞

我目前的解决方法是把 $_conn 变量声明成了静态的了,所有调用 $this->_conn 都改成了 self::_conn,好像达到了我的目的,但不知道有什么弊端没有,望各位大神不吝赐教。

查看完整回答
反对 回复 2019-03-18
?
呼如林

TA贡献1798条经验 获得超3个赞

//这句是不是释放链接? 如果是去掉
$this->release();  
查看完整回答
反对 回复 2019-03-18
  • 3 回答
  • 0 关注
  • 442 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信