Sbioko
Sbioko

Reputation: 107

Is it good, that every PHP class implements a Singleton pattern

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!

Upvotes: 1

Views: 464

Answers (6)

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

It is possible, it just would not be OOP design. OOP is meant to simplify structing with 3 main properties: inheritance (ie common classes share the same interface), polymorphism (ie subclassing) and encapsulation (ie having a blackbox approach to your objects).

Singleton, although they can be extended and abstracted, usually aren't so that basically takes OOP goodies out of your reach. It would be some sort of original procedural programming with everything namespaced in global scope.

Upvotes: 0

Kemo
Kemo

Reputation: 7042

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

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

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134157

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.

Upvotes: 1

Michael Ekstrand
Michael Ekstrand

Reputation: 29090

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?

Upvotes: 8

neo
neo

Reputation: 1270

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.

Upvotes: 1

Jhonny D. Cano -Leftware-
Jhonny D. Cano -Leftware-

Reputation: 18013

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.

Upvotes: 10

Related Questions