Set $mysqli as a global variable for OOP

2019-07-09 09:37发布

问题:

Ok, This is sort of an involved problem, but any help or advice would be incredibly appreciated.

So I'm working with a site that (using .htaccess) redirects all traffic to a load.php. For any sql functionality, I have an abstract class that has a lot of query statements as functions that pass parameters to define the specifics of each query.

e.g. $table->update("constraints")

I'm trying to figure out how to set the connection to the database on load.php, and then set the connection as a variable ($mysqli) that can then be referenced in my abstract query class without having to pass the parameter to every single query function call.

Again, any help or advice would be appreciated.

Here's an example of a function:

 function clearTable (){
    $mysqli = dbConnect::connect();
    $sql = "TRUNCATE TABLE $this->tablename";
    $mysqli->query($sql);

}

If I connect to the database in a construct function and set $this->mysqli and replace $mysqli = dbConnect::connect(); with $mysqli = $this->mysqli, none of the queries work. Though they work with a fresh reconnect on each call.

回答1:

You should use Dependency Injection for this.

Basically it means that the class that needs the database connection doesn't create the connection, it just receives the already instasiated instance.

Example

In some init file:

// Create the db connection
$db = new Mysqli(......);

// Pass it to the query class that needs it
$queryClass = new QueryClass($db);

Then in your class file:

class QueryClass
{
    protected $db;

    public function __construct($db)
    {
        // $this->db will now be the same Mysql instance
        $this->db = $db;
    }

    public function doSomeQuery()
    {
        $this->db->query(....);
    }
}

A bonus for this is that you don't need to touch the QueryClass, if you ever want to start making some unit tests. You only need to pass a DB connection to a test database instead.



回答2:

After looking through this a bit more, I can also create my db::connect() function to look like this:

class dbConnect {
    private static $db;
    private $mysqli;
    private function __construct() {
        $this->mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    }
    function __destruct() {
        $this->mysqli->close();
    }
    public static function connect() {
        if (self::$db == null) {
            self::$db = new dbConnect();
        }
        return self::$db->mysqli;
    }
} 

and pass that as $this->mysqli in the query functions file