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

前端 未结 10 941
野的像风
野的像风 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:43

    You could use an singleton pattern to achive this and request everytime you need the database a database object. This results in something like this

    $db = DB::instance();
    

    where DB::instance is declared something like this

    class DB {
    
        //...
    
        private static $instance;    
    
        public static function instance() {
            if (self::$instance == null) {
                self::$instance = new self();
            }
        }
    
        //...
    
    }
    

提交回复
热议问题