Trying to use database connection with singleton. __constructor has been private and returning instance from static function.
class MyDbConn
{
protected $_conn;
protected $database;
protected $user;
protected $password;
protected $host = "localhost";
private static $instance;
private function __construct()
{
$this->db_conn = new PDO("mysql:host=$this->host;dbname=$this->database",$this->user,$this->password);
$this->db_conn->exec("set names utf8");
$this->_conn = $this->db_conn;
}
public static function returnInstance() {
if(self::$instance == null)
{
print "Object created!";
self::$instance = new self;
}
return self::$instance;
}
public function returnconnection(){
return $this->_connection;
}
}
Now I can access the connection instance from MyDbConn::returnInstance()->returnconnection();
But,
How do I pass my users detail and database name to this constructor ?? I cannot do ::returnInstance($username,$password) or returnconnection($username,$password).
Any ideas please.
Answer
You can do it using global or with a normal function call
class MyDbConn
{
protected $_conn;
protected $database;
protected $user;
protected $password;
protected $host = "localhost";
private static $instance;
private function __construct()
{
}
public static function returnInstance() {
if(self::$instance == null)
{
print "Object created!";
self::$instance = new self;
}
return self::$instance;
}
private static function initDatabase(){
$database = self::returnInstance();
global $config;
$database->_conn = new PDO("mysql:host={$config['host']};dbname={$config['database']}",$config['user'],$config['password']);
$database->_conn->exec("set names utf8");
return $database;
}
public static function returnconnection(){
try {
$db = self::initDatabase();
return $db->_conn;
} catch (Exception $ex) {
echo "Error Establishing Database Connection " . $ex->getMessage();
return null;
}
}
}
and pass the data like this
// will be called from initDatabase using global keyword
$config = array('host' => 'localhost', 'database' => 'db name','user' => 'user here','password' => '');
$db = MyDbConn::returnconnection();
I don't recommend Singleton, and i suggest using Dependency Injection
No comments:
Post a Comment