views:

284

answers:

2

Perhaps you can help. I have a main class that creates a MySql connection. Then I extend this class. I wasn't able to access the connection unless I did a parent::__construct(); and recently while doing this I got an error message that I was out of connections.

So how do program this so it doesn't run out of connections and can access the database connection.

class Common 
{
    var $mysql;

    function __construct()
    { 
     $this->mysql=new mysqli($this->dbHOST, $this->dbUSERNAME, $this->dbPASSWORD, $this->dbNAME);
    }
}

class Role extends Common {

    function __construct()
    {
     parent::__construct();
    }
}
A: 

Make sure you close the connection when the object is destroyed. That is, add a __destruct() method that closes the connection.

If the Common class is the one that opens the connection in its __construct() method, then it should be the one to close it in its __destruct() method. If you don't define a __destruct() method on the Role class, then it looks like PHP won't call the parent's __destruct() automatically. (I haven't tested this, though.) A simple solution is to add a stub __destruct() method that just calls parent::__destruct().

Daniel Pryden
A: 

I think there is a fundamental problem with your class structure: You don't need a connection per object, you only need a copy of the connection resource per object.

My preferred way out of this is to create a database handler that has a singleton call. Now it can be called anywhere and it will always return the same connection handler. This is also an excellent way to hide automatic initialization.

The solution was borne out of the realization that a class representing a database row is actually quite different from a class that is a database connection. An app will deal with many many rows but rarely, if ever, will deal with more than one connection. Another way of putting this is the difference between the IS-A and HAS-A definitions: it doesn't make sense to say "a database row class IS-A database connection". It does make sense to say "a datbase row class HAS-A database connection".

staticsan
Thanks! I used the following for a reference in singleton call.http://dev.thatspoppycock.com/index.php/Creating_a_MySQL_Database_Class_Using_the_Singleton_Design_Pattern
John
That's a great starting point. I would extend the static function slightly, however, to always make the DB connection. That way the calling code doesn't have to worry about that: it just calls the singleton function and it will always have a working connection.
staticsan