I would like to know if creating a class like the one below would be a good practice.
So I would use the self::$mysqli object every time I need to do some work and the connection would only get closed on __desctruct(). Plus, extending the class would still maintain only one connection since $mysqli is declared static.
this way I would have only one connection thought the script
class db {
protected static $mysqli;
function __contruct(){
$this->mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
// DB_HOST, DB_USER, DB_PASS, DB_DATABASE defined elsewhere
}
function __destruct(){
$this->mysqli->close();
}
}
I would like to know your insights about this.
I would consider it not to be good practice. That’s especially for one reason: the problem you describe why you think you need it: Only one connection per request.
You don’t need to code anything.
mysqlihas a nice feature build in, the default connection. It picks the database connection parameters from the ini settings (configuration) each time you create a new instance:As all database connections get closed when the script finishes, there is not much to care about at all. The only thing you need to do is to instantiate the connection once and pass the variable around to all code that needs that
mysqliobject.Another bad practice is that you’re introducing a Singleton Doc here, something like:
It would work like this:
and would always return that one mysqli instance, which might be what you’re looking for. However Singletons are considered harmful as they can introduce a lot of problems see the related question Who needs singletons?.
It’s easier you create yourself a variable that you pass around containing the database instance. You can additionally encapsulate some sort of lazy-loading in case your application does not always need a mysqli connection, e.g. with a very simple context class:
When your scripts start, just instantiate your context and pass it to every part of your code where you need it:
This suggestion might be a little shortsighted as well, but it’s better than a singleton while not introducing much ado. The benefit is that you have encapsulated the logic when to create the
mysqliobject w/o the need of a singleton. Your code is now independent to global or static context.