Re: Abstracting a database class
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.php archive

Re: Abstracting a database class

From: Lüpher Cypher <lupher.cypher@verizon.net>
Date: Sun Jan 01 2006 - 02:32:50 CET

Full Decent wrote:
> Hey all!
>
> I've been using PHP for a while and I'm hearing that I should look into
> using it OO. I'm looking into making changes to the program Camera Life
> (http://fdcl.sf.net). I want to abstract the connection to the database
> which is currently MYSQL and maybe implement another database, or just
> leave it open for addition. If I get lucky and get the hang of this,
> I'd also like to abstract calls to GD.
>
> So firstly, is there a good solution to this problem? I've seen many
> examples, but many of them are incomplete or simply academic. Also,
> will I lose any functionality by doing it this way? I am currently
> using a complicated SELECT statement with a CONCAT. Will this be
> possible with the abstracted class?
>
> Thanks for your consideration,
> FD
>

I would definetely consider it :) For instance, if you use mysql and
then need to move the site to another server with a different dbms, I
bet you'd hate to change all those mysql_* calls :)
So, off the top of the head, I'd go with something like

class DB {
   function DB($host,$db,$user,$pwd) {
     $this->host = $host;
     $this->db = $db;
     $this->user = $user;
     $this->pwd = $pwd;
   }

   function connect() {
     // abstract
   }

   ...

   function query($query) {
     // abstract
   }

   ...
}

class DBMySql extends DB {
   function connect() {
     mysql_connect($this-host,$this->user,$this->pwd);
     mysql_select_db($this->db);
   }
   ...
}

class DBPostgreSql extends DB {
   function connect() {
     pg_connect("host=$this->host dbname=$this->db user=$this->user
password=$this->pwd");
   }
   ...
}

and so on. Then in any place you want to use database, assume you are
using class DB:

...
/**
  * @var DB
  * @access private
  */
var $db;
...

Then instantiate it to whatever you use:

...
$this->db = new DBMySql("localhost","test","user","pwd");
...
$this->connect(); // works for any database now
...

Then, if you move to another database, simply change which class you
instantiate.

As for the SQL statments, I'd say there could be a problem if the syntax
differs in different dbms. For instance, in Oracle to get current date
one would call sysdate(), and in ms-sql - getdate(). In this case you
may want to consider aliases for function names which are replaced when
query() method is called.

luph
Received on Tue Jan 3 03:51:21 2006