mardi 7 août 2018

How to use singleton pattern class in other classes in php

I made singleton class for connection with database

class Database {

private static $instance = null;
private $conn;

private function __construct() {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
    $this->conn = new PDO($dsn, DB_USER, DB_PASS);
}

private function __clone() {
    return false;
}

private function __wakeup() {
    return false;
}

public static function getInstance() {
    if(!self::$instance) {
        self::$instance = new Database();
    }
    return self::$instance;
}
public function getConnection() {
    return $this->conn;
}}

So, my question is: I need to use this object in other classes, should i create object separately and pass it, and let the constructor of other classes take him, like this:

$db  = Database::getInstance();
$user = new User($db);

Or, should i extend User class with Database class and create connection in User class constructor?

Aucun commentaire:

Enregistrer un commentaire