| re: Shared DB connection + classes
"bobo" <bobo@someaddress.com> wrote in message
news:Xns95E2813F8DFA3bobobobo@134.58.127.12...[color=blue]
> Hi Group,
>
> I've got a small web interface, basically a link index with
> different categories.I use different classes for HTML rendering,
> category managing, link managing etcetera.
>
> Now, most of these classes need DB access, but it's best to limit
> the DB connections per requested page (no?). So I've got two ideas
> here:[/color]
Pass the db database connect to the object method when it needs it. This is
the most flexible approach, since it opens up the possibility of the objects
retrieving data from different databases. It also makes more sense
linguistically. The database is not a component of your objects. Your
objects "make use of" or "operate on" the database. By passing the database
object as a parameter you indicate this clearly. Consider the following
scenario:
We have object $A of class A and object $B of class B. We also have $DB--the
database object, which both classes have access to by through a reference or
a singleton. We are presented with the following fragment:
$A->Panda();
$B->Dingo();
$A->Panda();
Panda() reads from $DB. On the first call it gets 5 rows; the second times
it gets 0. But what happened? Why is $DB behaving differently all of a
sudden? The answer is obvious, of course: the dingo has deleted the row. But
we don't see that in the code. All we see is a method invocation on $B,
which is understood to be changing only the state of $B. $B is basically
causing an action at a distance--cool in physics, not good for code clarity. |