MySQLi class pattern for connection, close, leave

2019-08-11 20:00发布

问题:

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.

回答1:

I would like to know if creating a class like the one below would be a good practice.

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. mysqli has 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:

$db = new mysqli;

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 mysqli object.

Another bad practice is that you're introducing a Singleton Doc here, something like:

class MysqliSingleton extends mysqli
{
    private static $instance;
    /**
     * @return MysqliSingleton
     */
    public function getInstance()
    {
        if (NULL === self::$instance)
            self::$instance = new self();
        return self::$instance;
    }
    private function __construct()
    {
    }
    public function __clone()
    {
         throw new RuntimeException('Clone is not allowed.');
    }
    public function __wakeup()
    {
        throw new RuntimeException('Unserializing is not allowed.');
    }
}

It would work like this:

$mysqli = MysqliSingleton::getInstance();

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:

interface ContextMysqli
{
    /**
     * @return mysqli
     */
    public function getMysqli();
}

class Context implements ContextMysqli
{
    private $mysqli;
    public function getMysqli()
    {
        $this->mysqli || $this->mysqli = new mysqli();
        return $this->mysqli;
    }
}

When your scripts start, just instantiate your context and pass it to every part of your code where you need it:

$context = new Context();
...
$result = do_some_db_work($context);
...
function do_some_db_work(ContextMysqli $context)
{
    $mysqli = $context->getMysqli();
    ...
}

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 mysqli object w/o the need of a singleton. Your code is now independent to global or static context.



回答2:

When PHP finishes executing, it will close all connections automatically so there is no need to explicitly close the connection unless optimizing a rather large system or where memory usage must be kept to an absolute minimum.

What you have setup above will only ever keep on connection open, you could look into the singleton pattern, but that is seriously overkill for this basic use case.

That being said, there's no harm in closing it at the end :)