OO Singletons
Posted: Thu Mar 13, 2008 12:55 am
Code: Select all
<?php
function emptyEx()
{
if (!(func_num_args() > 0))
{
return NULL;
}
$args = func_get_args();
foreach ($args as $tmp)
{
if (empty($tmp))
{
return 1;
}
}
return 0;
}
class database
{
private static $db_handle;
private static $class_instance;
private function __construct()
{
require_once('config/db_conf.php');
$this->db_handle = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS)
or exit(mysql_error());
mysql_select_db(MYSQL_DB)
or exit(mysql_error());
}
public static function initialize()
{
if (!isset(self::$class_instance))
{
$class_name = __CLASS__;
self::$class_instance = new $class_name;
}
return self::$class_instance;
}
function query($sql)
{
if (empty($sql))
{
return NULL; //NO query given.
}
else
{
$results = mysql_query($sql);
}
if ($results === TRUE)
{
return 1;
}
if ($results === FALSE)
{
return 0;
}
if (mysql_num_rows($results) == 1 && mysql_num_fields($results) == 1)
{
$results = mysql_fetch_row($results);
return $results[0];
}
while ($tmp = mysql_fetch_assoc($results))
{
$resultArr[] = $tmp;
}
if (is_array($resultArr[0]) && count($resultArr) == 1)
{
return $resultArr[0];
}
return $resultArr;
}
function result_count($table, $row = NULL, $match1 = NULL, $match2 = NULL)
{
if (empty($row))
{
$row = '*';
}
$sql = "SELECT count($row) FROM $table";
if (!empty($match1) && empty($match2))
{
$sql .= " WHERE $row = '$match1'";
}
if (!emptyEx($match1, $match2))
{
$sql .= " WHERE $match1 = '$match2'";
}
$results = $this->query($sql);
return $results;
}
function __destruct()
{
mysql_close($this->db_handle);
}
}
$db_handle = database::initialize();
class user_handle {
function __construct($db_handle)
{
$this->db_handle = $db_handle;
}
function return_all_users()
{
$result = $this->db_handle->query("SELECT * FROM userinfo");
print_r($result);
}
}
$user_handle = new user_handle($db_handle);
$user_handle->return_all_users();
?>