Re: Any idea how to do it right?



ralphz wrote:
Hi Jerry.

Thanks for your reply. I was thinking about making a singleton and then use it in my classes constructor to get database object but that would mean three things.

1. I would have to hard code name of database classes (singletons) in other classes.


Not necessarily. You can pass them to methods as necessary. But even if you do hard code it in the class, that's not necessarily bad. You can derive a database class from the "real" database class, i.e.

class RealDatabaseName {
... stuff here
}
class DatabaseObjectUsed extends RealDatabaseName {
... nothing required here
}

Now if you change databases, all you need to do is change the parent of DatabaseObjectUsed.

2. Require to configure singleton classes, at the beginning of every script, even if database connection is not used every time script is running.


Why? I use them a lot, but only make the connection when it's actually needed, i.e.

class MyClass {
private $db = null;

__construct($db = null) {
$this->db = $db;
}

private function getDb() {
if ($this->db == null)
$this->db = DatabaseObjectUsed::getSingleton();
return $this->db;
}

public function funcUsingDb () {
$db = $this->getDb();
... use database here
}
}

You can either pass a database object to the constructor (optional - leave it out if you don't want it). But the key is you only get the object when you're going to use it. If you never use it, you never make the connection.

3. Singletons would work as global variables so would be accessible at any time to every peace of code. PHP classes have global scope.


Not really a problem, because you have control over singletons. You have no control over global variables. I don't use global variables, but I use singletons a lot.

One advantage of singletons is you don't have to pass the database object to the class. This makes the class more self-sufficient - the rest of the program doesn't need to worry about where the data is stored.

Another advantage is that you don't have to make multiple connections to the same database.

I was hoping for some nice method to pass database abstraction objects in constructor, but that would mean passing a lot of parameters to aggregate class.


You can do that, of course.


Ralph


The question comes to mind - why do you have so many different databases? If the data in them are related, they should be different tables in one database. Perhaps your database design could be improved.


--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@xxxxxxxxxxxxx
==================

.