Hi, I've been playing around with an old (simple) database class i'd written a while back and I want to improve my understanding of OOP, so i'm trying to improve the design to make it as reusable as possible. I know PDO is available as an abstraction layer, but this is mainly for learning purposes so i'd be interested in any feedback.
I decided to use an abstract class, instead of an interface, as there is a level of implementation i can add to the constructor of the abstract class and which can apply to any extending classes (mysql, postgres etc).
This can obviously be fleshed out to add a lot more flexibility and functionality but at the moment i want to make sure i have the general design right and am not misunderstanding any of the concepts.
mysql.phpPHP Code:abstract class Database {
protected $config;
public function __construct(Config $conf) {
$this->set_config($conf)
->connect()
->select_db();
}
protected function set_config($conf)
{
$this->config = $conf;
return $this;
}
abstract protected function connect();
abstract protected function select_db();
abstract public function query($query);
abstract public function fetch_assoc($queryResource);
abstract protected function disconnect();
abstract protected function error_code();
}
I'm also wondering if there's a neater way to handle any errors from the query or fetch_assoc methods, other than an if/else statement - i.e in my return statement can i do something like this (even though i know this particular statement doesn't work):PHP Code:class Mysql extends Database {
private $db;
private $link;
protected function connect()
{
$this->link = mysql_connect($this->config->hostname, $this->config->username, $this->config->password);
if ( ! $this->link)
{
return $this->error_code();
}
return $this;
}
protected function select_db()
{
$this->db = mysql_select_db($this->config->database);
if ( ! $this->db)
{
return $this->error_code();
}
}
public function query($qry) {
return mysql_query($qry);
}
public function fetch_assoc($res) {
return mysql_fetch_assoc($res);
}
protected function error_code() {
return mysql_error($this->link);
}
protected function disconnect() {
is_resource($this->link) and mysql_close($this->link);
}
}
PHP Code:return mysql_error($this->link) OR $this->error_code();






Bookmarks