views:

123

answers:

5

Hello, is it good, that every PHP class implements a Singleton pattern? I think, it will be less memory usage because of it. Is it right opinion? Thanks!

+9  A: 

Software is meant to model the reality. that's the way the OOP exists. that said, Singleton is not a hammer for all nails. You can use it in certain models, but there are others which simply will not adjust.

Take for example, model a list of persons. If you decide to create a Person class, then you will not be allowed to have more than one person on your model.

Jhonny D. Cano -Leftware-
+1  A: 

There is a simple rule: If it's definitly sure that a class is only to be used once, implement Singleton. If it needs to be used more than once, don't do it.

If your programm has only classes with one single instance it looks like a major code smell and is not suitable for object-oriented programming.

neo
+7  A: 

If all your classes are singletons, why use classes?

Singletons are useful in some cases, but tend to be over-used. If you can get away with singletons, then you probably don't need classes for their intended object-oriented uses. They can still be useful for code modularization, though.

In general, classes are most useful when you do have multiple instances of the class. Classes are blueprints for objects, so you can create many objects with similar behavior but, typically, different internal state.

So, if all your classes are Singletons, I would step back and ask a couple questions:

  • Do you need classes?
  • Are you thinking correctly about how your software models the problem you're trying to solve?
Michael E
+1  A: 

This seems like a very bad idea. I would recommend keeping any data you need between requests in a session (if per user) or a cache (if per server). As far as memory usage, it should not make that much of a difference.

Justin Ethier
A: 

Actually it is (combined with factory), take Kohana 3 Framework for example;

it uses singleton / factory combination where ever it's possible.

Kemo