如何避免使用OOP PHP打开与数据库的多个连接 [英] How to avoid opening multiple connections to the DB with OOP PHP

查看:75
本文介绍了如何避免使用OOP PHP打开与数据库的多个连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成为程序程序员超过4年了,是时候开始研究OOP了.这样说,假设我需要在类中调用两个方法.每种方法都需要与数据库的连接,因此与数据库的连接需要两次,这也会打开多个连接. 可以通过在应用程序层(构造函数)中使用某种代码来避免这种情况,还是必须在数据库侧设置连接池?只是为了踢,我没有使用mysql.我正在将mongodb与codeigniter一起使用.

I've been a procedural programmer for over 4 yrs and it's time to start looking into OOP. With that said, let's say I needed to call two methods in my class. Each method requires a connection to the DB so that's two trips to the DB, which also opens multiple connections. Can this be avoided by having some sort of code in the application layer (constructor?) or does a connection pool have to be setup on the DB side? And just for kicks, I'm not using mysql; I'm using mongodb with codeigniter.

到目前为止,这是我所拥有的,不确定使用是否理想?

Here's what I have so far, not sure if it's ideal to use?

在这里设置我的数据库信息:

Here's where I setup my DB info:

database_conn.php

class Database_Conn extends Model {

    function _connect() {
        $m = new Mongo("localhost:27017", array("persist"=>"x"));
        $db = $m->selectDB( "foo" );
        return $db;
    }    
}     

样本模型文件

class Home_model extends Model {

    public function __construct() {
        // Establish connection to "profiles" table
        $this->db_conn = Database_Conn::_connect()->selectCollection( "profiles" );
    }

    function getMyProfile($username) {
        $data = $this->db_conn->findOne(array("username" => $username) );
        return $data;
    }

    function getAll() {
        $data = $this->db_conn->find(); 
        return $data;
    }
}

推荐答案

您应该使用单人模式

按照您的操作方式,可以多次调用_connect,这意味着重新连接.

the way you did it, it is possible to call _connect multiple times, which means reconnecting.

单个实现通常意味着您必须将构造函数设为私有/受保护,并定义一个getInstance方法,该方法在第一次调用时创建连接,并在以后的调用中返回创建的连接.

singleton implementation usually means you have to make constructor private/protected and define a getInstance method which creates connection on first call and returns the created connection on later calls.

这就是我要做的:

class Database_Conn extends Model {

    static protected $_instance;

    protected $db = null;

    final protected function __construct() {
        $m = new Mongo("localhost:27017", array("persist"=>"x"));
        $this->db = $m->selectDB( "foo" );
    }

    static public function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function getConnection() {
        return $this->db;
    }

    final protected function __clone() { }
}

,然后使用Database_Conn::getInstance()->getConnection()获取连接对象.

and then use Database_Conn::getInstance()->getConnection() to get the connection object.

这篇关于如何避免使用OOP PHP打开与数据库的多个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆