?
Solved

DataBase Connection Class, Maintain Static Connection Variable??

Posted on 2004-11-15
5
Medium Priority
?
319 Views
Last Modified: 2008-01-09
Hello, I had this problem in PHP 4 and Squinky offered a solution with globals, but now that I'm using PHP 5 I'd like to implement a solution with a static class variable, but I'm not sure how.  Here is the original question I posted, with an addition at the bottom:

****old question**********************************************************
Problem:

I have several data classes that all extend a parent "DBObject" class.

The "Connect_DB()" function is in the DBObject class, and all the children inherit it.  However, I need a way to only allow ONE db Connection through the DBObject class, no matter how many times it is called by the children.

The specific problem is that class Company has a member variable, which is a type of class Collection.  Now, both Company and Collection extend DBObject, so what inevitably ends up happening, is that Company creates a new DBObject, and SO DOES Collection.  Then there are 2 DBConnections.

How can I maintain a global static DBOjbect that all the children can use, but not accidently create a second instance, or override the first connection?

If the entire OO design I have sounds funny, your critique in that regard is welcome as well.

Thanks,
Scott
***********************************************************************

I don't mind new connections being created by different objects in the system i.e.  if you navigate to the 'viewUser.php' page, the UserCollection class would create it's own connection to the DB.  If you then navigated to the 'viewProject.php' page, the ProjectCollection class would create a NEW connection to the DB...I don't want to persist the DB connection one time per session or anything like that.

Here is the problem:
ProjectCollection has a delete() method...which is basically this:
foreach(ProjectCollection as $objProject)
  $objProject->delete();

In this case, I'd like each of the $objProject objects inside the collection to use the ONE DB connection that ProjectCollection would have initialized when the page loaded.  I could probably pass a flag to each of my object's delete methods telling the child not to connect to the database itself, but I'm looking for a more elegant OO solution, where the children 'KNOW' that they are inside a collection and don't need to connect each time one of a hundred objects gets deleted by the collection object itself.

Thanks for your insights.

Scott.

ps, again, if you have alternative OO design solutions that you'd like to add, I'd love to hear them.
0
Comment
Question by:kbach
  • 3
  • 2
5 Comments
 
LVL 48

Accepted Solution

by:
hernst42 earned 800 total points
ID: 12588463
Just a pratical note. If you use mysql and connect in one script to the same host with the same user and password, a new connection is only made to the db-server is you set the 4th parameter to true.

The Typical OO design is that your object use a DB-Object and do not inherit from that object.
class DBObject {
 function delete($table, $condition){
     //generate SQL and execute sql
  }

  function &sigleton() {
    static $dbObj = null;
    if (is_null($dbObj)) {
        $dbObj = new DBObject();
        // settings taken from a include, ..
        $dbObj->setConnection($host, $user, $passw);
    }
    return $dbObj;
}

class Collelction{
    var $_db;
    function Collection() {
        $this->_db = DBObject::singelton();
    }
    function delete() {
       $this->_db->delete('MyTable', "Id=" . $this->ID);
    }
}

So you have only one DB-Object with one connection. And its still OO.
Just my 2 cents
0
 
LVL 1

Author Comment

by:kbach
ID: 12589155
Thanks,

Question: did you use a static $dbObj variable inside the function singleton() out of habit because PHP 4 didn't support static class variables?  In other words, in PHP 5 could I avoid the need for the singleton function altogether by declaring a static class variable and having that returned by a getLink() function?

Thanks.
sk
0
 
LVL 1

Author Comment

by:kbach
ID: 12589350
I didn't realize that mysql used the same link unless you explicitly tell it to create a new connection.  This means that my original code was working the way I wanted it, which is one connection per script execution.

I like your idea of the singleton method, but I'd like to keep the DataObject class as a parent class for all my dataObject subclasses, as they are just that, DB objects and are never used for anything except CRUD methods.

This way, I can always have a reference to $this->dbConnection no matter how many levels deep in the hierarchy I go.  With an external DB class that is a composite of each of my data classes, I'd have to explicity get a link when I need it by going to the singleton function.

What I DO like about the singleton though is that it EXPLICITLY forces the db connection only once, and doesn't defer responsiblity to mysql itself.  Again though, I'd like protected access to the $link returned by the static method, without having to call the singleton each time.

I tried to emulate the same functionality by declaring a static CLASS variable, and checking if that was null inside my Connect() routine, which would do what the singleton does, BUT give all children access to $this->link without having to return a link each time.

I didn't have any success though, so seeing as I'm just wasting time, I'll leave my original code in there, and defer to mysql to handle whether it's a new connection or not.

In the future though, if anyone has code for me to declare a static class $_db object instead of the static function variable, that would allow me access to it through all levels without recalling the singleton function when I want the reference.

Thanks hernst42, I'm learning more every day :-).
0
 
LVL 1

Author Comment

by:kbach
ID: 12600327
hernst42, or anyone else:

Do you know if the mysql_connect() rule mentioned above (use the same link if called twice in same script) applies to the new mysqli_connect() function recently added?  I need to change my code to use this newer c api as I'm using stored procedures now in Mysql 5 and need extra params...

Just a question.
Thanks.
0
 
LVL 48

Expert Comment

by:hernst42
ID: 12608453
as far I can see the mysqli_connect will make a new connection every time. So you should use a DB-Object instead of inherit from the DB-class.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question