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

前端 未结 3 2032
失恋的感觉
失恋的感觉 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 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.

提交回复
热议问题