par
nightkid83 » 12 sept. 2008, 05:04
Salut tout le monde, je viens de créer une classe pour me connecter à une base de données MySQL, sachant que je ne suis qu'un novice dans la programmation orienté objet, j'aimerai avoir votre avis deçu (ce que je pourrais ajouter comme enlever... etc). Merci
<?php
class DatabaseConnection
{
private static $_instance = null;
private $_host = 'localhost';
private $_dbname = 'nightkid';
private $_user = 'root';
private $_password = '';
private $_handle = null;
private function __construct()
{
$this->connect();
}
public function __destruct()
{
$this->disconnect();
}
public function __clone()
{
try {
throw new Exception('Clone is not allowed');
} catch (Exception $e) {
die('Caught exception : ' . $e->getMessage());
}
}
private function connect()
{
try {
$this->_handle = new PDO("mysql:host=$this->_host;dbname=$this->_dbname", $this->_user, $this->_password);
$this->_handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connection established and database "' . $this->_dbname . '" selected.';
} catch (PDOException $e) {
die('Connection failed or database cannot be selected : ' . $e->getMessage());
}
}
private function disconnect()
{
if ($this->_handle !== null) {
$this->_handle = null;
// echo 'Connection closed.';
}
}
public static function getInstance()
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function getHandle()
{
return $this->_handle;
}
}
Salut tout le monde, je viens de créer une classe pour me connecter à une base de données MySQL, sachant que je ne suis qu'un novice dans la programmation orienté objet, j'aimerai avoir votre avis deçu (ce que je pourrais ajouter comme enlever... etc). Merci
[php]
<?php
class DatabaseConnection
{
private static $_instance = null;
private $_host = 'localhost';
private $_dbname = 'nightkid';
private $_user = 'root';
private $_password = '';
private $_handle = null;
private function __construct()
{
$this->connect();
}
public function __destruct()
{
$this->disconnect();
}
public function __clone()
{
try {
throw new Exception('Clone is not allowed');
} catch (Exception $e) {
die('Caught exception : ' . $e->getMessage());
}
}
private function connect()
{
try {
$this->_handle = new PDO("mysql:host=$this->_host;dbname=$this->_dbname", $this->_user, $this->_password);
$this->_handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connection established and database "' . $this->_dbname . '" selected.';
} catch (PDOException $e) {
die('Connection failed or database cannot be selected : ' . $e->getMessage());
}
}
private function disconnect()
{
if ($this->_handle !== null) {
$this->_handle = null;
// echo 'Connection closed.';
}
}
public static function getInstance()
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function getHandle()
{
return $this->_handle;
}
}
[/php]