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');
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.