How to avoid opening multiple connections to the DB with OOP PHP

前端 未结 3 2033
失恋的感觉
失恋的感觉 2021-02-09 10:35

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 requ

相关标签:
3条回答
  • 2021-02-09 10:51

    You should look into a manager class for your db connections. Then you can have one central place where you request connections from. If there is already an open connection the manager can return that instead of returning a new connection.

    This would be one approach. There are tons of examples out there about how to implement something like this. There already some for mysql and mssql. But you could surely extend for your db.

    0 讨论(0)
  • 2021-02-09 10:51

    Use a database layer. Dibi is a great library in this case. http://dibiphp.com

    0 讨论(0)
  • 2021-02-09 11:01

    you should use singleton pattern

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

    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.

    this is what i would do:

    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() { }
    }
    

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

    0 讨论(0)
提交回复
热议问题