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

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

    Here is an example of a simple approach:

    class Database {
      public $connection = null ;
    
      public function __construct($autosetup = false){
        if ($autosetup){
          $this->setConnection() ;
        }
      }
    
      public function getProducts(){//Move it to another class if you wish
        $this->query($sql_to_get_products);
      }
    
      public function query($sql) {
        if (!$connection || !$connection->ping()){
          $this->setupConnection() ;
        }
        return $this->connection->query($sql);
      }
    
      public function setConnection(){
        $this->connection = new MySQLi($a, $b, $c, $d) ;
      }
    
      public function connectionAvailable(){
        return ($connection && $connection->ping()) ;
      }
    }
    

提交回复
热议问题