|
Posted by Chung Leong on 11/16/05 01:49
Anonymous via the Cypherpunks Tonga Remailer wrote:
> Hi,
>
> I'm building a simple Object Oriented CMS using PHP5
> and the new object model (new to both). I'm looking
> for some design advice on how best to integrate the
> database class - which creates the db connection and
> executes the sql queries. In my particular case,
> I have 3 objects (classes) that I instantiate from
> a given script (call it index.php). Each must have
> access to the database. So, do I create a db connection
> once and declare it 'global' in the various classes?
> or do I create a db connection in each class - maybe
> in the constructor? or is there some other practice
> that's widely accepted? Any recommendations are
> greatly appreciated.
Don't use global variables if you can help it. They create runtime
dependencies in your code, making your code less reuseable and harder
to understand/debug.
A general technique I use for such situations is to call a function to
retrieve the database connection. The function itself would use a
static variable to cache the handler, so that it wouldn't need to go
through the same motion when it's called again:
function GetDatabaseConnection() {
static $connection;
if(is_null($connection)) {
/* open the connection */
$connection = ???
}
return $connection;
}
Another way to model it is to pass the database connection in each
call:
getVisitor($dbconn);
That gives your more flexibility, since your code could potentially
operate on different databases.
>
> <?php
> // index.php
> $dbconn = csite::DB();
>
> $a = new cvisitor();
> $b = new cvalid8r();
> $c = new cnode();
>
> ... blah blah
> ?>
>
> <?php
> // cvisitor.php
> class cvisitor {
> public function __construct() {
> }
> public function __destruct() {
> }
>
> public function getVisitor() {
> // open the db
> global $dbconn;
>
> ... do the db stuff
> ?>
>
> Thanks,
> b
[Back to original message]
|