44.7. Singleton, MySQLi Examples

Example 44.5.  Database Singleton, Params

<?php
/* 
 * Project Specific DbP.inc.php
 * @author nml
 */
abstract class DbP {
    const DBHOST = 'localhost';
    const DBUSER = 'nobody';
    const USERPWD = 'test';
    const DB = 'world'; 
    const DSN = "mysql:host=".self::DBHOST.";dbname=".self::DB;
}

Example 44.6. Database Singleton, Class

<?php
/**
 * Project Agnostic DbH.inc.php with MySQLi
 * @author nml
 * @copyright (c) 2018, nml
 * @license http://www.fsf.org/licensing/ GPLv3
 */
require_once 'DbP.inc.php';

class DbH extends DbP {
    private static $dbh;

    private function __construct() {}

    public static function getDbH() {
        if (empty(self::$dbh)) {
            try {
                self::$dbh = new mysqli(DbP::DBHOST, DbP::DBUSER, DbP::USERPWD, DbP::DB);
            } catch(mysqli_sql_exception $e) {
                die(sprintf("<p>Connect failed for following reason: <br/>%s: %s</p>\n",
                  $e->getCode(), $e->getMessage()));
            }
        }         
        return self::$dbh;
    }
}

Example 44.7. Calling Sequence

<?php
    require_once 'DbH.inc.php';    
    //...
    $DBH = DbH::getDBH();
    $result = $DBH->query('select ....');
    //...