Bringing DB connection into Object

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
arpowers
Forum Commoner
Posts: 76
Joined: Sun Oct 14, 2007 10:05 pm
Location: san diego, ca

Bringing DB connection into Object

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Bringing DB connection into Object

Post 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( .. );
Post Reply