Giorgio Sironi’s Blog: How to eliminate singletons

Singletons are often compared to same class of evil as goto instruction, or more familiar for PHP developers $GLOBALS. This thesis is hard to understand since Singleton is most basic and commonly know pattern. Even if one agrees with arguments, might find hard to eliminate singletons from own code. Giorgio Sironi shows that eliminating singletons is not that hard.

It is actually very simple to eliminate singletons: just force the components to ask for what they need in the constructor or via setters or via inject*() methods, instead of looking up a singleton trough a static method only to obtain a reference. Once this fundamental decoupling is achieved, the hard part is tackling the construction problem: Zend Framework has a big codebase and writing a factory (manual dependency injection) for every use case is not viable. Thus, automatic dependency injection needs to be called upon. There are many xml-configured dependency injection frameworks for php to incorporate, but let’s show a simple example of how they works.

The tutorial was split into two parts. First one presents basic solution for the problem. Second part addresses some problems related to objects having shorter lifetime than application-wide ones.