tags:

views:

52

answers:

4

I need some help in planning out how to do my classes in PHP. I have a session class and a database class that I pretty much need to access inside of every other class I use (forums, mail, users, lots more classes)

So I am looking for how I should access the session class inside of my other classes, 1 option is to make it GLOBAL, another is to pass $session and $database objects into every class I use like this...

$mail = new Mail($session, $database);

but this seems pretty tedious if I have to do it for 15+ different classes? Is there a better way?

Below is an example of some methods from my sessions class that I would be calling inside of other classes.

// set a value into session
$session->set('auto_id', 'some value for auto_id');

// get a value from session
$session->get('auto_id');
A: 

For things like sessions and databases, I think global variables are fine here.

GSto
+2  A: 

For scenarios like this i would make use of the registry pattern. This is a pretty good explanation.

The registry pattern acts like a storage for objects.

A code example is on it's way.

Edit:

In your example (new Mail($session, $database)), i think you should do this even if you use the registry pattern. This makes every thing less coupled and easier to understand and change parts independently. As I have not done so much PHP in the last couple of years, i don't know if there is any IOC-framework available, but that would help you instantiating your classes.

alexn
Doesn't the registry object end up being a singleton/global?
jmucchiello
+1  A: 

I'd have thought the singleton pattern would be a very good fit in this instance.

There's a nice simple tutorial (with some sample code) over at talkPHP that seems like a reasonable implementation.

middaparka
A: 

I disagree completely with using globals. I would either use the Registry pattern as suggested or make both the Session and DB themselves Singletons, although this will make unit testing much more difficult.

prodigitalson