23

Possible Duplicate:
Who needs singletons?

I always write with respect to best practice, but I also want to understand why a given thing is a best practice.

I've read on in an article (I unfortunately don't remember) that singleton classes are prefered to be instantiated, rather than being made with static functions and accessed with the scope resolution operator (::). So if I have a class that contains all my tools to validate, in short:

class validate {
    private function __construct(){}
    public static function email($input){
        return true;
    }
}

I've been told this is considered bad practice (or at least warned against), because of such things as the garbage collector and maintenance. So what the critiques of the "singleton class as static methods" wants, is that I instantiate a class I'm 100% certain I will only ever instantiate once. To me it seems like doing "double work", because it's all ready there. What am I missing?

What's the view on the matter? Of course it's not a life and death issue, but one might as well do a thing the right way, if the option is there :)

Community
  • 1
  • 1
Jens
  • 1,078
  • 1
  • 9
  • 19

3 Answers3

51

An example singleton classes in php:
Creating the Singleton design pattern in PHP5 : Ans 1 :
Creating the Singleton design pattern in PHP5 : Ans 2 :

Singleton is considered "bad practice".

Mainly because of this: How is testing the registry pattern or singleton hard in PHP?

Wanna read more? :

A Singleton decision diagram (source):

Singleton Decision Diagram

Community
  • 1
  • 1
ThinkingMonkey
  • 12,011
  • 12
  • 51
  • 80
  • 1
    Thanks for the links; Already reading them. I think I might have mis-interpreted what a singleton is though (which is pointed out in the reply below) – Jens Jan 08 '12 at 10:56
  • @MarkHünermundJensen Thought so reading your question. Tats why posted the links ;). – ThinkingMonkey Jan 08 '12 at 11:04
  • 1
    Please note Dependency Injection does not equal Dependency Injection Container. DI is definitely a good thing; DIC is one way of implementing this and isn't necessarily a one-size-fits-all solution (despite the fact that it's much "in vogue" in the PHP world at the moment). A Service Locator or similar pattern might also be an acceptable way to break dependencies. – liquorvicar Jan 08 '12 at 11:17
  • Thanks again! They are very helpful :) – Jens Jan 08 '12 at 11:22
  • @ThinkingMonkey Might be worth including a link to Martin Fowler's excellent post on the subject just for completeness ;-) http://martinfowler.com/articles/injection.html – liquorvicar Jan 08 '12 at 11:27
  • @liquorvicar Yup you are right thats an excellent article. Doing it now :) – ThinkingMonkey Jan 08 '12 at 11:34
  • 2
    given that this post merely collects links from SO and external sites, I think it should be a Community Wiki. – Gordon Jan 08 '12 at 11:48
  • 1
    @gordon Community Wiki done :). – ThinkingMonkey Jan 08 '12 at 11:53
  • I think that it is GOOD to use Singleton if you know when you need to use it. I am using a Singleton as a Request Class, it is easy to use, it will never need a second instance and I need to use it anyway in all the pages. e.g. Request::get(param,param...), Request::post(param,param...). In this case I really do not need a class, why creating an instance, one instance already double the memory. If you are a good developer you just need to know when and why to use this kind of things. – Roy Shoa Nov 23 '14 at 16:33
  • Singletons can still be valid approach and useful in some cases. For example, when building an AST tree representing some code, and if you want each predefined programming language keyword in that AST to be the same instance of class, so that no duplicate objects are created for each instance of the keyword. Does it make sense to you? – Meglio Nov 16 '20 at 11:22
6

A singleton object is an object that is only instantiated once. That is not the same as the Singleton Pattern, which is a (Anti-) Pattern how to write a class that can be only instantiated once, the Singleton (large S at the beginning):

“Ensure a class has only one instance, and provide a global point of access to it.”

As far as PHP is concerned, you normally do not need to implement the Singleton Pattern. In fact you should avoid to do that when you ask for best practice, because it is bad practice.

Additionally most PHP code examples you find are half-ready implementations of the pattern that neglect how PHP works. These bogus implementations do not go conform with the "ensure" in the pattern.

This also tells something: Often that it is not needed. If a sloppy implementation does the work already while not even coming close to what the pattern is for, the wrong pattern has been used for the situation, it's starting to become an Anti-Pattern.

In PHP there normally is no need to ensure at all costs that a class has only one instance, PHP applications are not that complex that you would need that (e.g. there are no multiple threads which might need to refer to an atomic instance).

What is often left is the global access point to the class instance, which is for what most PHP developers (mis-) use the pattern. As it's known as-of today, using such "Singletons" lead to the standard problems of global static state that introduce complexity into your code across multiple levels and decrease re-usability. As a programmer you loose the ability to use your code in a flexible way. But flexbility is a very important technique to solve problems. And programmers are solving problems the whole day long.

So before applying a Design Pattern the pro and cons need to be evaluated. Just using some pattern most often is not helpful.

For starters I would say, just write your classes and take care how and when they are instantiated in some other part of your application logic so things are kept flexible.

hakre
  • 178,314
  • 47
  • 389
  • 754
  • 4
    Your first phrase is contradictory :) . -1 . Also -1 for "PHP applications are not that complex" . You can write complex software using any language . Design patterns are related to the software architecture not to the underlaieing technology . I would triplle downvote but i can't . :) – Geo C. Jan 26 '14 at 08:54
  • @Geo C. One reason why I wrote so is that PHP applications normally do not need atomicity across processes and threads which are one use-case of thread-safe singletons in *more* complex software. You perhaps judge too fast because you think that did attack some specific language, but that's not the case. It's just that common PHP code does not need the implementation of the pattern. In case you still need it, I even offer that pattern on my blog. – hakre Jan 26 '14 at 10:02
2

Well, this isn't actually a singleton; a singleton ensures that you only have a single instance of a class, and there is no method here that would retrieve a single instance of Validate. Your design here appears to be a static class. This will not cause an issue with the garbage collector (at least the code you've placed here), because this would be loaded into memory no matter what.

Steve Rukuts
  • 8,609
  • 3
  • 43
  • 67
  • That would certainly explain why I can't find logic in that this sort of class would be a problem. So a singleton is not per say a class that is only instantiated once, but the method is -also- only called once? – Jens Jan 08 '12 at 10:57