Friday, July 24

PHP Singleton pattern for a database class

An example of how you would implement a Singleton pattern for a database class can be seen below:

<?php
class Database implements Singleton {
    private static $instance;
    private $pdo;

    private function __construct() {
        $this->pdo = new PDO(
            "mysql:host=localhost;dbname=database",
            "user",
            "password"
        );
    }

    public static function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance->pdo;
    }
}
?>
You would make use of the class in the following manner:

<?php
$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");

// ...

$db = Database::getInstance();
// $db is the same instance as before
?>

And for reference, the Singleton interface would look like:
<?php
interface Singleton {
    public static function getInstance();
}
?>

No comments:

Post a Comment