I have written a class that connects to a database using MySQLi and has methods for the connection itself and returns the instance of the MySQLi class.
This works, but feels a little "clunky" and can be a bit slow, can someone help me to improve this?
The class is as follows:
<?php
/**
* Connect to a db.
*/
class mysqli_connector
{
/** Private to implement Singleton pattern */
private function __construct() { }
private static $init;
/** @return mysqli_connector */
public static function Init()
{
return static::$init = (
null === static::$init ? new self() : static::$init
);
}
/** @var mysqli */
private static $link;
/**
* Sets and gets the link to the database based on params
* @param string $host
* @param string $username
* @param string $password
* @param string $dbname
* @return mysqli
*/
public function link($host = '', $username = '', $password = '', $dbname = '')
{
static::$link = mysqli_init();
if ($host != '' && $username != '' && $password != '' && $dbname != '')
{
static::$link->real_connect($host, $username, $password, $dbname);
}
else if ($host != '' && $username != '' && $password != '' && $dbname == '')
{
static::$link->real_connect($host, $username, $password);
}
else if ($host != '' && $username != '' && $password == '' && $dbname == '')
{
static::$link->real_connect($host, $username);
}
else if ($host != '' && $username == '' && $password == '' && $dbname == '')
{
static::$link->real_connect($host);
}
else
{
static::$link->real_connect();
}
return static::$link;
}
}
EDIT
I use the class as such:
<?php
require_once 'include/class/_db/mysqli-connector.php';
$connector = mysqli_connector::Init();
$link = $connector->link("myhost", "mysuser", "mypass", "mydbname");
var_dump($link); # Make sure it works!
?>
Output from the var_dump($link);
object(mysqli)[2]
public 'affected_rows' => int 0
public 'client_info' => string 'mysqlnd 5.0.11-dev - 20120503 - $Id: /* removed for security */ $' (length=79)
public 'client_version' => int 50011
public 'connect_errno' => int 0
public 'connect_error' => null
public 'errno' => int 0
public 'error' => string '' (length=0)
public 'error_list' =>
array (size=0)
empty
public 'field_count' => int 0
public 'host_info' => string 'localhost via TCP/IP' (length=20)
public 'info' => null
public 'insert_id' => int 0
public 'server_info' => string '5.6.26' (length=6)
public 'server_version' => int 50626
public 'stat' => string 'Uptime: 118450 Threads: 1 Questions: 149 Slow queries: 0 Opens: 70 Flush tables: 1 Open tables: 63 Queries per second avg: 0.001' (length=135)
public 'sqlstate' => string '00000' (length=5)
public 'protocol_version' => int 10
public 'thread_id' => int 117
public 'warning_count' => int 0