I have just been introduced to PEAR and it very interesting to read and learn about it.
I am in the way of creating a new website and I think PEAR could help me but I have some questions before I start coding.
I have studied Joe Stump PEAR article on phpbuilder and it is really interesting.
He has a Base class which extends PEAR class and a user Class which extends the Base class. The user class have methods in order to check if a user is a admin in the database.
This is not very hard to understand.
But what happens when you have more classes that also need to access the database?
Let say you are writing a guestbook and you have a class called Messages. In the Message class you have methods which read messages from the database.
The Message class should also extend the Base class, but when you create the Message object, you will also open a new connection to the database!
Isn't it better to use the connection which is already created?
Why don't write a new Sql Class and when you are creating the User object and Message object you send an reference to your database object instead. In that way the two objects can share the same database object!
Isn't that a good solution?
But here you have a problem (or not?)
Let me explain...
The own Sql class should exend PEAR Class. If not you don't have the pear_error handling? Right?
The object destructor should disconnect from the database, just like Joe Stumps script. It is good programming...
Now you have a little problem to solve. How do you use the methods in the PEAR DB Class?
Example
Main
<?
$db_obj =& new Sql("mysql://user:password@localhost/database");
$myUser_obj =& new MyUser ($db_obj);
$myUser_obj->ListUser();
?>
That was a short main...
Here are the Classes
<?
class Sql extends PEAR
{
var $db;
function Sql($dsn)
{
$this->PEAR();
$this->db =& DB::connect($dsn,true);
if (!DB::isError($this->db)) {
$this->db->setFetchMode(DB_FETCHMODE_ASSOC);
}
}
function _Sql()
{
if(!DB::isError($this->db)){
$this->db->disconnect();
}
}
}
?>
That was not really hard?
Ok lets see another class using Sql Class
<?
Class MyUser Extends PEAR
{
var $_db_obj; // Used as a reference to the database object
function MyUser($db_obj)
{
$this->_db_obj=$db_obj;
$this->PEAR();
}
function ListUser()
{
$sql = "SELECT U_Username
FROM w3t_Users";
$result = $_db_obj->db->query($sql);
if(!DB::isError($result) && $result->numRows()) {
return $result->fetchRow();
}
}
}
?>
My problem here is the statement
$result = $_db_obj->db->query($sql);
I don't think this is good programming since I am "dribbling" inside another object, I want it to look like this instead
$result = $_db_obj->query($sql);
How can I do all this without to do anything in another object. I want to call methods in the $db_obj object instead of $db_obj->db->
Any suggestions?
This was maybe a very nested question, sorry about that 🙂
Best regards
/Erik