Design Patterns: How to create database object/connection only when needed?

前端 未结 10 959
野的像风
野的像风 2020-11-29 21:04

I\'ve a simple application, say it has some classes and an \"extra\" one that handles database requests. Currently i\'m creating the database object everytime the app is use

10条回答
  •  一生所求
    2020-11-29 21:47

    This is approximately what I use.

    class Database {
    
        protected static $connection;
    
        // this could be public if you wanted to be able to get at the core database
        // set the class variable if it hasn't been done and return it
        protected function getConnection(){
            if (!isset(self::$connection)){
                self::$connection = new mysqli($args);
            }
            return self::$connection;
        }
        // proxy property get to contained object 
        public function __get($property){
            return $this->getConnection()->__get($property);
        }
        // proxy property set to contained object
        public function __set($property, $value){
            $this->getConnection()->__set($property, $value);
        }
    
        // proxy method calls to the contained object
        public function __call($method, $args){
            return call_user_func_array(array($this->getConnection(), $method), $args);
        }
    
        // proxy static method calls to the contained object
        public function __callStatic($method, $args){
            $connClass = get_class($this->getConnection());
            return call_user_func_array(array($connClass, $method), $args);
        }
    }
    

    Note it only works if there is a single database in play. If you wanted multiple different databases it would be possible to extend this but beware of late static binding in the getConnection method.

提交回复
热议问题