HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

PHP Database class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
databasephpclass

Problem

Below is the code for a database class that wraps around a small set of the features that the mysqli extension provides. I'm looking for ways to improve its efficiency. Which parts of the code seem hack-ish and how can I make it more structured and organized?

```
class Database extends Component
{
private static $mysqli = null; // MySQLi object

/ Connect to the database /
public static function init()
{
if (Config::read('Database.enable'))
{
if (!self::connect(Config::read('Database.connections')))
trigger_error('Database::connect() failed : Unable to connect to database', E_USER_ERROR);
}
}

/ Close the database connection upon script determination /
public function __destruct()
{
if (self::$mysqli)
self::$mysqli->close();
}

/ Returns the type label (i, d, s, b) of an array of MySQLi input parameters /
private static function getTypeLabel(array $args)
{
$return = '';

foreach ($args as $input)
{
if (is_int($input))
$return .= 'i';

else if (is_double($input) || is_float($input))
$return .= 'd';

else if (is_string($input))
$return .= 's';

else
$return .= 'b';
}

return $return;
}

/ Returns whether the MySQL connection has been established /
public static function connected()
{
return is_resource(self::$mysqli);
}

/ Returns the MySQL connection resource /
public static function obj()
{
return self::$mysqli;
}

/ Pass an array of login credentials and attempts to connect to the database /
public static function connect($db_list)
{
foreach ($db_list as $db)
{
self::$mysqli = @(new mysqli($db['host'], $db['user'], $db['pass'], $db['db']));
if (mysqli_connect_er

Solution

It looks like you are trying to write object oriented code, however this is completely procedural. Remove static everywhere and use dependency injection if you want to make this OO.

Static code is hard to test. It is the equivalent a namespaced function.

The real benefit I see with OO is encapsulation and implementation hiding. This allows a program to be split into objects that can interact while sharing a small public interface (and hiding a lot of implementation details in protected and private methods). The problem with static is that it opens up all of the implementation details globally. It stops you being able to look at an object and just be worried about its public interface.

Calling a static function binds the calling code tightly to a specific implementation. Database::query is a much tighter binding than having injected a database object and then calling $this->db->query

Context

StackExchange Code Review Q#7658, answer score: 5

Revisions (0)

No revisions yet.