I'm trying to create a simple to use singleton class to connect to mysql database and do queries, the code works fine and i haven't had any problems with it, but since I'm new to OOP I'm wondering whether this is bad practice or not.
Here's the class
class Database {
private $databaseName = 'dbname';
private $host = 'localhost';
private $user = 'user';
private $password = 'pass';
private static $instance; //store the single instance of the database
private function __construct(){
//This will load only once regardless of how many times the class is called
$connection = mysql_connect($this->host, $this->user, $this->password) or die (mysql_error());
$db = mysql_select_db($this->databaseName, $connection) or die(mysql_error());
echo 'DB initiated<br>';
}
//this function makes sure there's only 1 instance of the Database class
public static function getInstance(){
if(!self::$instance){
self::$instance = new Database();
}
return self::$instance;
}
public function connect() {
//db connection
}
public function query($query) {
//queries
$sql = mysql_query($query) or die(mysql_error());
return $sql;
}
public function numrows($query) {
//count number of rows
$sql = $this->query($query);
return mysql_num_rows($sql);
}
}
//Intantiate the class
$database = Database::getInstance();
and when i want to use the class I would do:
$query = "SELECT * FROM registrations";
echo $database->numrows($query);
$sql = $database->query($query);
A DB connection should not normally be a Singleton. Two reasons: many DB drivers are not thread safe. Using a singleton means that if you have many threads, they will all share the same connection.
Singleton Pattern ensures that a class has only one instance and provides a global point to access it. It ensures that only one object is available all across the application in a controlled state.
Singletons are bad news.
You're better off looking at dependency-injection instead, as it resolves the above issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With