I created registration system with PHP. I have User class that will handle all the input and insert the user input into database, and i created Database class with Singleton pattern that will connect to database. After user submited his data, new User object is created.
This is my Database class with singleton patter:
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;
}
}
And this is my User class:
class User {
public $errors = array();
protected $username;
protected $pw1;
protected $pw2;
protected $mail;
private $db;
private $conn;
public function __construct() {
$this->db = Database::getInstance();
$this->conn = $this->db->getConnection();
}
}
I didn't copied rest of the User class code, because my question is: Is this a good way to create singleton pattern for db connection, and a good way to use it in other classes? I'm fairly new to PHP, and i understand good amount of writing the PHP code, but what i lack is practical knowledge, what are common practices and how to structure the code.