UltraMega Blog
1Sep/110

Creating A Database Connection On Demand

It may be useful to only create a database connection when you actually use it for the sake of efficiency. Here is a wrapper for MySQLi that does just that in the most simple way I could devise. A (possibly desired) side-effect is that this limits you to a single connection.

How you pass in the connection details is up to you. You can hard-code them into the mysqli initialization, put them in class constants, or pass them into a constructor that sets static properties.

<?php
/**
 * Wrapper for MySQLi
 *
 * Creates a database connection on demand
 */
class DB {
    private static $db;
    private function connect() {
        if(!isset(self::$db)) {
            self::$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        }
    }
    public function __call($name, $arguments) {
        $this->connect();
        return call_user_func_array(array(self::$db, $name), $arguments);
    }
    public function __get($name) {
        $this->connect();
        return self::$db->$name;
    }
    public function __set($name, $value) {
        $this->connect();
        self::$db->$name = $value;
    }
    public function __isset($name) {
        $this->connect();
        return isset(self::$db->$name);
    }
    public function __unset($name) {
        $this->connect();
        unset(self::$db->$name);
    }
}

Usage:

<?php
$db = new DB(); // functionally identical to a mysqli object
$db->query('...');
Tagged as: , , , No Comments