Forum Moderators: coopster
I've been coding in PHP for several years now, and I come from a procedural background. I saw the need for functions and all, but never really saw the need to learn OOP. Now I do.
I've since built a few small classes, but now I'm looking to build some bigger classes that need to use the database. I have been using PEAR::MDB2 for awhile now.
My question: what is the best way to use a current MDB2 connection inside of your class? I would rather use a current connection (I think) then update my classes to have their own db connection methods. Or is that wrong thinking? Do I pass a reference to it when I create a new object?
Anyway, if you're an OOP expert, I could use some advice before continuing.
TIA!
That is what I have seen from some opensource work ive done. Readup on the zenframework. Im sure whatever they are doing is prolly as good as it gets.
So I'm guessing I would do something similar?
class testClass {
...
function testMethod() {
global $dbConn; // MDB2 database object
$query = $dbConn->query("SELECT * FROM table");
...
}
}
For each method I would need my db connection, I would simply do the global call?
Thanks again!
Database::query("SELECT * FROM table"); ("Database" should be the name of your db class). [edited by: RonPK at 10:32 pm (utc) on Nov. 17, 2008]
class mydb{
function connect($host, $pass, $etc..){
//i would want to make this link global, but this
//is normal connection
$this->link = @mysql_connect($host, $pass, etc...);
return true.
}
function my_query($sql){
$result = mysql_query($sql,$this->link);
return $result;
}
}
in my php file:
mydbObj = new mydb;
mydbObj->connect($host, $pass, $ect);
$result = mydbObj->my_query($sql);
now a connection has been made to db, and we have preformed a query. I think the connection is available, so instead of $result line, we could just do this:
$result = mysql_query($query);
not sure though. Anyway I hope this helps. There are a lot of people who have written different db classes. Dont know much about it though
Again, OOP is new to me and I'm looking for the best way to do it, so I learn the right way from the beginning. My old way of just using functions I have done it both ways. I was just wondering from an OOP perspective the best way to use objects from others classes in your code.
Thanks again to all!