Hej! :)
Sitter och pillar lite med en databas-klass och skulle vilja veta vilken av följande lösningar som är att föredra? Klassen är skriven i PHP men jag anser att frågan i sig är generell för objektorienterad programmering.
Första lösningen har attribut för MySQL databasen och anslutning sker via constructorn med ett anrop till funktionen connect().
<?php
class MySQL {
private $host; // MySQL server host address
private $user; // MySQL username
private $password; // MySQL password
private $database; // Name of the MySQL database to use
private $connection; // MySQL resource link identifier
private $connectError;
/**
* MySQL constructor. Attempts to establish a connection to the specified
* database by invoking the connect function.
*
* @param string $host
* @param string $user
* @param string $password
* @param string $database
*/
public function __construct($host, $user, $password, $database) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->connect();
}
/**
* Establishes a connection to a MySQL server and selects a database.
* Maybe it shall throw exceptions?
*
* @return void
*/
private function connect() {
if(!$this->connection = @mysql_connect($this->host,
$this->user, $this->password)) {
//trigger_error('Could not connect to the server');
//$this->connectError = true;
throw new RuntimeException(mysql_error());
}
else if(!mysql_select_db($this->database, $this->connection)) {
trigger_error('Could not select the database');
$this->connectError = true;
}
else {
echo 'connected!';
}
}
/**
* Closes the connection to MySql server and the database (optional)
*
* @return void
*/
public function close() {
$this->connection = mysql_close($this->connection);
}
}
//test
$db = new MySQL('localhost', 'plump_it4hujo', 'kakelikaka', 'plump_testDB');
?>
Denna lösning har inga attribut för host/user/pass/db och anslutningen görs direkt i constructorn.
<?php
class MySQL {
private $connection; // MySQL resource link identifier
private $connectError;
/**
* MySQL constructor. Attempts to establish a connection to the specified
* database by invoking the connect function.
*
* @param string $host
* @param string $user
* @param string $password
* @param string $database
*/
public function __construct($host, $user, $password, $database) {
if(!$this->connection = @mysql_connect($host,
$user, $password)) {
//trigger_error('Could not connect to the server');
//$this->connectError = true;
throw new RuntimeException(mysql_error());
}
else if(!mysql_select_db($database, $this->connection)) {
trigger_error('Could not select the database');
$this->connectError = true;
}
else {
echo 'connected!';
}
}
/**
* Closes the connection to MySql server and the database (optional)
*
* @return void
*/
public function close() {
$this->connection = mysql_close($this->connection);
}
}
?>
Det skulle vara intressant att höra vilken lösning ni anser vara den bästa.