How do you organize and manage your helper objects like the database engine, user notification, error handling and so on in a PHP based, object oriented project?
Say I have a large PHP CMS. The CMS is organized in various classes. A few examples:
- the database object
- user management
- an API to create/modify/delete items
- a messaging object to display messages to the end user
- a context handler that takes you to the right page
- a navigation bar class that shows buttons
- a logging object
- possibly, custom error handling
I am dealing with the eternal question, how to best make these objects accessible to each part of the system that needs it.
my first apporach, many years ago was to have a $application global that contained initialized instances of these classes.
global $application; $application->messageHandler->addMessage("Item successfully inserted");
I then changed over to the Singleton pattern and a factory function:
$mh =&factory("messageHandler"); $mh->addMessage("Item successfully inserted");
but I'm not happy with that either. Unit tests and encapsulation become more and more important to me, and in my understanding the logic behind globals/singletons destroys the basic idea of OOP.
Then there is of course the possibility of giving each object a number of pointers to the helper objects it needs, probably the very cleanest, resource-saving and testing-friendly way but I have doubts about the maintainability of this in the long run.
Most PHP frameworks I have looked into use either the singleton pattern, or functions that access the initialized objects. Both fine approaches, but as I said I'm happy with neither.
I would like to broaden my horizon on what common patterns exist here. I am looking for examples, additional ideas and pointers towards resources that discuss this from a long-term, real-world perspective.
Also, I'm interested to hear about specialized, niche or plain weird approaches to the issue.