I would avoid the Singleton approach suggested by Flavius. There are numerous reasons to avoid this approach. It violates good OOP principles. The google testing blog has some good articles on the Singleton and how to avoid it:
http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-join-new-project.html
http://googletesting.blogspot.com/2008/05/tott-using-dependancy-injection-to.html
http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html
Alternatives
-
a service provider
http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html
-
dependency injection
http://en.wikipedia.org/wiki/Dependency_injection
and a php explanation:
http://components.symfony-project.org/dependency-injection/trunk/book/01-Dependency-Injection
This is a good article about these alternatives:
http://martinfowler.com/articles/injection.html
Implementing dependency injection (DI):
-
I believe you should ask what is needed in the constructor for the object to function:
new YourObject($dependencyA, $dependencyB);
-
You can provide the needed objects (dependencies) manually (
$application = new Application(new MessageHandler()
). But you can also use a DI framework (the wikipedia page provides links to PHP DI frameworks).Important is that you only pass in what you actually use (call an action on), NOT what you simply pass to other objects because they need it. Here’s a recent post from ‘uncle Bob’ (Robert Martin) discussing manual DI vs using framework.
Some more thoughts on Flavius’s solution. I don’t want this post to be an anti-post but I think it’s important to see why dependency injection is, at least for me, better than globals.
Even though it is not a ‘true’ Singleton implementation, I still think Flavius got it wrong. Global state is bad. Note that such solutions also use difficult to test static methods.
I know a lot of people do it, approve it and use it. But reading Misko Heverys blog articles (a google testability expert), rereading it and slowly digesting what he says did alter the way I see design a lot.
If you want to be able to test you application, you’ll need to adopt a different approach to designing your application. When you do test-first programming, you’ll have difficulty with things like this: ‘next I want to implement logging in this piece of code; let’s write a test first that logs a basic message’ and then come up with a test that forces you to write and use a global logger that can’t be replaced.
I am still struggling with all the information I got from that blog, and it’s not always easy to implement, and I have many questions. But there’s no way I can go back to what I did before (yes, global state and Singletons (big S)) after I grasped what Misko Hevery was saying 🙂