I am building a model in Zend to build an object with key data, which will be lazyloaded as required and stored in a session variable.
I am considering the singleton pattern, but find some of the material unclear on the cons. The singleton appears to persist and act like a global. But in a HTTP environment (unless it is stored in a session or database) would presumably only last as long as the request.
I want to authenticate the user, store the userid etc in private variables and as the current user acesses information i.e. current address store that as well to save database calls.
Am I right that the singleton only lasts as long as the session and that each subsequent user could make a singleton for themselves?
Thoughts on pros and cons appreciated.
Your question is not really clear but a Singleton would disappear between each request, it’s just a kind (pattern) of class, if you do nothing to preserve it between calls to your server it will disappear.
The cons around singletons are it often reflects a bad design : singletons are bringing stuff static. But a good OOP design is suppose to keep things private and modular, thus it should have very few coupling between classes. If many classes are used everywhere, then you might have something wrong.
TMHO if you have one or two singletons in your app to maintain a global request context and a user context, that’s fine. If you have ten of them, you might need to redesign some parts of your app.