Php singleton database connection, is this code bad practice?

I am trying to create an easy-to-use singleton class to connect to the mysql database and make queries, the code works fine and I had no problems with it, but since I'm new to OOP, I think it's bad practice or not.

Here is 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 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);
+5
source share
5 answers

Singleton is bad news.

  • They introduce a global state into the program. Most programmers should know why the global state is bad.
  • , . , , , .
  • , , singleton .
  • , . , , .
  • PHP " ", , PHP , ( ).
  • , - , , ? , .

, .

+12

, singleton , .

, . , .

( ) . ; .

"", MySQL , msSQL, sqlite - , .

+2

, singleton . , . , , , , .

0

The only positive argument I heard for the Singleton design pattern in PHP is the developer who implemented the Singleton database connection in conjunction with the Memcached object. In fact, I did not have the opportunity to look at the code and performance, but he was able to output a consistent argument.

Personally, I do not think that the Singleton design template is very important for PHP, which in any case is largely stateless (as indicated above, when each request will have one singleton).

0
source

All Articles