Re: Any idea how to do it right?
- From: Jerry Stuckle <jstucklex@xxxxxxxxxxxxx>
- Date: Tue, 29 Apr 2008 19:21:38 -0400
ralphz wrote:
Help! Too much classes :)
I hit the brick wall when designing something. It seams I can't find the way to solve a problem in elegant way.
I have multiple classes that use database to access or validate data. To manage creating the database connection and fetching data I use database abstraction layer
class. Everything is fine when I instantiate classes directly:
$s = new ClassName();
In this case I can design class to take database object as a constructor parameter or define method of the class that takes database abstraction object and makes class aware of database.
The problem arises when I use aggregate class (composite class?) that encapsulates many other objects that may use different databases. How to pass database connection settings or database abstraction layer object to objects being part of aggregate object?
Ralph
Ralph,
You might want to investigate singletons. Each reference to a database can be a singleton, i.e.
class database1 {
private static $db = null;
... other stuff here
static getSingleton() {
if ($db == null) {
if (($db=mysql_connect('localhost', userid', 'password')) &&
mysql_select_db('dbname'))
$this->db = $db;
else
echo mysql_error();
}
return $this->db;
}
... other functions
}
Where you need to access the database, just use:
function uses_database() {
$db = database1::getSingleton();
if ($db) {
do your work here
}
else
graceful exit here
}
(I don't like using die(). It's very user unfriendly!).
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@xxxxxxxxxxxxx
==================
.
- Follow-Ups:
- Re: Any idea how to do it right?
- From: ralphz
- Re: Any idea how to do it right?
- References:
- Any idea how to do it right?
- From: ralphz
- Any idea how to do it right?
- Prev by Date: Any idea how to do it right?
- Next by Date: I've been hacked, help!
- Previous by thread: Any idea how to do it right?
- Next by thread: Re: Any idea how to do it right?
- Index(es):
Relevant Pages
|