NYCPHP Meetup

NYPHP.org

[nycphp-talk] Accessing a method from one class in another

Kenneth Downs ken at secdat.com
Sat Jan 14 13:01:02 EST 2006


There are two real issues here.

But, these are obscured by the OO factor.  First off, OO does not make
code any more re-usable than procedural code, you just use it differently.
 The problem you are hitting would be the same if you were using
procedural code, which is A) Variable scoping and B) organizining of
subroutines.

So first you have to tackle the issue of scoping the connection to the DB.
 I myself use a global connection handle that is opened at request start
and closed at request end.  This has the benefit of being simplest correct
way in my context.  But if this is not appropriate to your context, the
you will have to obtain the handle and then pass it around to those
routines that need it.

The next issue is proper decomposition of the subroutines.  This again is
the same in OO vs. Procedural.  Perhaps there should be data retrieval
routines that pull information from a database, and separate rendering
routines that turn retrieved data into HTML.  Then its more clear that you
hand the DB handle to the data retrieval routines and they give you back
data, and then you hand that data to rendering routines.

Hope this helps.

> Coming from a procedural background, I've been able to move to the OOP
> way of doing things, but I am far from really mastering it, and making
> things as reusable as I probably can. One thing that always bugs me is
> how I access the DB object in all of the other classes.
>
> I always include and instantiate the DB this way:
>
> include 'class_db.php';
> $db = new DB;
> $db = $db->conn;//the db object is generated with the help of ADODB
>
> Then, in my other classes, like class_content(), I pass the $db to
> each method, like this:
>
> function addContent($db, $type)
> function viewContent($db, $rec)
> function updateContent($db, $rec)
>
> This works OK when I'm dealing with the DB object, but there are a
> couple of other classes, like class_image that I need to access in
> other classes as well. It doesn't make sense to have this...
>
> function addContent($db, $image, $type)
>
> ...so that I can have access to all of the methods for class_image
> inside of class_content.
>
> What is it that I'm not grasping?
>
> --
> Randal Rust
> R.Squared Communications
> www.r2communications.com
> _______________________________________________
> New York PHP Talk Mailing List
> AMP Technology
> Supporting Apache, MySQL and PHP
> http://lists.nyphp.org/mailman/listinfo/talk
> http://www.nyphp.org
>


-- 
Kenneth Downs
Secure Data Software
631-379-0010
ken at secdat.com
PO Box 708
East Setauket, NY 11733




More information about the talk mailing list