simple example of how to use a db access class

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm building a simple Object Oriented CMS using PHP5
and the new object model (new to both). I'm looking  
for some design advice on how best to integrate the
database class - which creates the db connection and  
executes the sql queries.  In my particular case,
I have 3 objects (classes) that I instantiate from
a given script (call it index.php). Each must have
access to the database. So, do I create a db connection  
once and declare it 'global' in the various classes?  
or do I create a db connection in each class - maybe
in the constructor? or is there some other practice  
that's widely accepted? Any recommendations are  
greatly appreciated.

    // index.php
    $dbconn = csite::DB();

    $a = new cvisitor();
    $b = new cvalid8r();
    $c = new cnode();

    ... blah blah

    // cvisitor.php
    class cvisitor {
    public function __construct() {
    public function __destruct() {
    public function getVisitor() {
      // open the db
      global $dbconn;

    ... do the db stuff


Re: simple example of how to use a db access class

Anonymous via the Cypherpunks Tonga Remailer wrote:
Quoted text here. Click to load it

Don't use global variables if you can help it. They create runtime
dependencies in your code, making your code less reuseable and harder
to understand/debug.

A general technique I use for such situations is to call a function to
retrieve the database connection. The function itself would use a
static variable to cache the handler, so that it wouldn't need to go
through the same motion when it's called again:

function GetDatabaseConnection() {
   static $connection;
   if(is_null($connection)) {

     /* open the connection */
    $connection = ???

   return $connection;

Another way to model it is to pass the database connection in each


That gives your more flexibility, since your code could potentially
operate on different databases.

Quoted text here. Click to load it

Site Timeline