Page 1 of 1

Bringing DB connection into Object

Posted: Sat Mar 15, 2008 9:33 pm
by arpowers
Hey Everyone,

quick question... what is the best way to bring in a database connection to an object.

for instance, right now I use
global $connection;
$this->connection = $connection;

I'm trying to use PDO (the php db abstraction tool)
with it a have to use something like this:
$this->connection = DBConn::get();
but then I have to use it like this:
$this->connection->fetchAll....
which is a little tedious.

I would like to know the most elegant way of referencing a connection in objects, with PDO or without.

Re: Bringing DB connection into Object

Posted: Sat Mar 15, 2008 10:16 pm
by John Cartwright
Using an abstraction layer, of course. Some connection may require an adapter to conform to a single interface, but that is a whole other topic.

Code: Select all

class DB_Abstraction
{
    public function __construct($db) 
    {
        $this->connection = $db;
    }
 
    public function query($sql) 
    {
        return $this->connection->query($sql);
    }
}
 
$connection = PDO::getConnection();
$db = new DB_Abstraction($connection);
$db->query( .. );