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

发布于 2022-09-07 22:47:04 字数 2596 浏览 50 评论 0

我写了一个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被实例化,就会产生多少次数据库链接。

求教如何改成我希望的那样呢?谢谢了。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

温柔戏命师 2022-09-14 22:47:04
static $_instance = null;
if ($_instance == null) {
    $_instance = new static($config);
}
return $_instance;
吻风 2022-09-14 22:47:04

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

幸福不弃 2022-09-14 22:47:04
//这句是不是释放链接? 如果是去掉
$this->release();  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文