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);
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.
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();
}
It is to my understanding that static methods DO NOT use the __construct method.
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.
To elaborate on a mysqli singleton:
You can then request the database connection by calling:
You can then retrieve the database connection in your own objects:
Here is one approach:
Create a singleton class, that can be accessed statically from anywhere.
An example would be:
Hovewer I suggest using another solution as well:
Then you could pass that object to other classes (constructor)
This is the shortest version I could come up with for Bootstrap 3.