Since I'm trying to get a better understanding, and since we seem to be mixing several issues here, let me try to clarify and see if you agree.
As per Wiki, a global variable is a variable that is accessible in every scope.... They are usually considered bad practice precisely because of their nonlocality: a global variable can potentially be modified from anywhere, (unless they reside in protected memory) and any part of the program may depend on it. A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity. Singletons are considered bad practice, when used as a form of universal data storage, because, like global variables, they have an unlimited potential for creating mutual dependencies. I realize some people are saying that Singletons should never be used. If that's the case, why are they used in Zend Framework? For example, Zend_Auth, Zend_Registry, Zend_Loader_Autoloader, and Zend_Controller_Front. Aren't these good examples of where Singletons are beneficial? How do you know when it's ok to use Singletons? It seems like Singletons are beneficial, when used to share a single resource, because they have the potential for improving performance, and reducing application complexity. Let me use Michael's Factory class as an example. Sure, you could probably rename the class Singleton for clarity. In fact, the getInstance method could be moved inside the class of the objects being generated through the Factory class. To demonstrate this, you'd create a class called Users that extends Zend_Db_Table and you'd give it a method called getInstance. Doing this, you would effectively create a shared resource that serves as a link to the Users database. Whenever you would use $Users = new Users(); You could instead use $Users = Users::getInstance(); That way, instead of reinstantiating an instance of Users all over the application, you call getInstance and re-use the same object as often as you'd like - giving the 7X performance boost Michael was mentioning. And then, adding to the idea a little here, instead of manually adding the getInstance method to every one of your Zend_Db_Table objects, you could create a base class with this method that you can extend from. Or, if you don't have PHP5.3, you can achieve the same thing by using the Factory class that Michael presented. It might seem like a minor adjustment to use a common instance of a Zend_Db_Table object when working with a specific table throughout your application. If that 7X performance boost reduces your page load from 49 seconds to 7 seconds, isn't it worth it? Yes - I realize there are other performance enhancements available as well, cacheing, etc., but this one seems worthwhile also. Or... am I just barking up the wrong tree and asking for trouble later on? Make sense? What do you think? Matthew? -Ed
