Reputation: 38342
What is the best way to move database connective outside this class. So that there is only 1 connection per execution. Also any improvements to the below code is welcome.
<?php
$DatabaseConfig = array(
'username' => 'root',
'password' => 'root',
'host' => 'localhost',
'database' => 'live'
);
define('APPPATH', '/var/www/');
require_once APPPATH.'lib/KLogger.php';
class BaseModel {
/**
* var $klogger object klogger instance
*/
protected $Klogger;
/**
* var $Mysqli object mysqli instance
*/
protected $DBH;
/**
* function to initiate logger and database
*/
function __construct()
{
$this->Klogger = KLogger::instance(APPPATH.'tmp/logs/mysql/', KLogger::INFO);
$this->initDb();
}
/**
* function to initiate database
*/
protected function initDb()
{
global $DatabaseConfig;
try{
$this->DBH = new PDO("mysql:host=".$DatabaseConfig['host'].";dbname=".$DatabaseConfig['database'],
$DatabaseConfig['username'], $DatabaseConfig['password']);
}
catch(PDOException $e){
$this->Klogger->logError($e->getMessage());
exit;
};
}
/**
* function to initiate database
*/
protected function fetch($query,$data = array())
{
try
{
$STH = $this->DBH->prepare($query);
$STH->execute();
$result = array();
while($row = $STH->fetch(PDO::FETCH_ASSOC)) {
$result[] =$row;
}
return $result;
}
catch(Exception $e){
$this->Klogger->logError($e->getMessage().' \n Query : '.$query);
return false;
};
}
/**
* function to save to database
*/
protected function save($query,$data = array())
{
try
{
if(empty($data))
{
throw new Exception('Data Not Passed To save');
}
$STH = $this->DBH->prepare($query);
$STH->execute($data);
return true;
}
catch(Exception $e){
$this->Klogger->logError($e->getMessage().' \n Query : '.$query);
return false;
};
}
}
?>
<?php
require_once 'base_model.php';
class profile extends BaseModel
{
function test()
{
$data = $this->fetch("SELECT * FROM users");
$result = $this->save("INSERT INTO users (name, age) VALUES (?,?)",array("tow",1));
var_dump($data);
var_dump($result);
}
}
$profile = new profile();
$profile->test();
?>
Upvotes: 0
Views: 256
Reputation: 929
You should look into the Singleton Design Pattern. Here's an example of a database connection singleton.
Upvotes: 1
Reputation: 2428
Moving database stuff outside class doesn't seem to be a good solution. Try to use Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern
Upvotes: 0