How static classes vs singleton (databases) work

I am confused about how the singleton vs static model works for database connections. My friend created a “static” class and showed it to me, but it made no sense how static it was. I understand the singleton method of how to create a database connection, but I'm not sure if it matches my purpose.

The main thing I want to do is to reduce the number of connections open to MYSQL. I have a class with a function that often calls the database, and there is no reason to create a new connection every time someone asks for what the database requires. Can someone provide a small sample class for this with a singleton or static method (depending on which one is suitable) that connects to the database and shows a small example query? I would be very grateful.

Oh yes, I am using PHP 5.3 :) Please feel free to ask for more information.

+3
source share
1 answer

, singleton ( )

class Database {

    protected static $_dbh;
    const HOST = 'localhost';
    const DATABASE = 'dbname';
    const USERNAME = 'username';
    const PASSWORD = 'password';

    //declare the constructor as private to avoid direct instantiation.   
    private function __construct() { }

    //access the database object through the getInstance method.
    public static function getInstance() {
        if(!isset($_dbh)) {
            #Connection String.
            self::$_dbh = new PDO('mysql:host='.self::HOST.';dbname='.self::DATABASE,self::USERNAME,self::PASSWORD);
            self::$_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        return self::$_dbh;
    }
}

, , .

require_once('database.php');
$dbh = Database::getInstance();
$sth = $dbh->query('SELECT * FROM sometable');
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

Database::getInstance(); . , , , . true, . . , .

+5

All Articles