创建一个全局可访问的 MySQLi 对象

2021-12-25 00:00:00 constructor php mysqli

我有多个使用静态方法的类.这些函数使用

I have multiple classes that use static methods. These functions connect to the database using

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

其中常量 DB_SERVER、DB_USER、DB_PASS、DB_NAME 是在全局可访问文件中定义的数据库变量.最近,我的网站开始变慢,在分析脚本后,我意识到创建对象 ($mysqli) 的调用导致了这个问题.

where the constants DB_SERVER, DB_USER, DB_PASS, DB_NAME are database variables defined in a globally accessible file. Recently, my site started becoming slow and after profiling the script I realized that the call to create the object($mysqli) was causing this problem.

我的大部分类都从 mysqli 扩展,使得

Most of my classes extend from mysqli such that

public function __construct($user_id) {
    parent::__construct(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    $this->retrieve_user_details($user_id);
    $this->check_user_account_type();

}

据我所知,静态方法不要使用 __construct 方法.

It is to my understanding that static methods DO NOT use the __construct method.

有人可以指导我如何创建 $mysqli 对象,以便所有需要它的静态方法都可以访问它.

Could someone guide me on how I can create the $mysqli object once such that it can be accessed by all static methods that require it.

推荐答案

这是一种方法:

创建一个可以从任何地方静态访问的单例类.

Create a singleton class, that can be accessed statically from anywhere.

class DBConnector {
    private static $instance ;
    public function __construct($host, $user, $password, $db){
      if (self::$instance){
        exit("Instance on DBConnection already exists.") ;
      }
    }

    public static function getInstance(){
      if (!self::$instance){
        self::$instance = new DBConnector(a,b,c,d) ;
      }
      return $instance ;
    }
}

一个例子是:

$mysqli = DBConnector::getInstance() ;

但是我建议也使用另一种解决方案:

$mysqli = new MySQLi(a,b,c,d) ;

然后你可以将该对象传递给其他类(构造函数)

Then you could pass that object to other classes (constructor)

class Shop {
  private $mysqli ;
  public function __construct(MySQLi $mysqli){
    $this->mysqli = $mysqli ;
  }
}

$show = new Shop($mysqli) ;

相关文章