3

I was wondering recently as to why everybody says you should avoid Singletons, so I read about it and it makes sense.

But I have noticed that a lot of popular Wordpress plugins are almost going Full Singletons in their design pattern.

For a developer trying to learn how to code properly by reading code of plugins written by experienced developers, it is very confusing why these plugins overused Singleton pattern. ie.: Woocommerce and much more.

Is there a benefit to use the Singleton pattern in some cases?

FluffyKitten
  • 13,824
  • 10
  • 39
  • 52
jayrchamp
  • 85
  • 1
  • 9
  • hmm, this is a bit of pitfall, singleton is not inherently bad -- just like a knife. perhaps there are some design consideration on using singletons, such as a known fact that php `static` variable lives for a single request so it can lessen bootstrapping a class if we had a single class. well, i hope some better devs can explain. – Bagus Tesa Sep 05 '17 at 01:41
  • Just a word of caution - I wouldn't assume all plugin developers are experienced in software engineering & design, especially as PHP can foster bad programming practices. You should use proper material so you don't pick up bad habits (...or at least understand why they are bad habits before you decide to use them anyway when you're up against it, as can happen in the code you are currently learning from!) – FluffyKitten Sep 05 '17 at 02:27

1 Answers1

1

Singletons aren't always bad it all depends on the context of their use. When you see something that has a Singleton you should ask yourself a few things.

  • Are they using a singleton because they cannot use a better pattern like a Factory or Dependency Injection
  • Are they using a singleton because their component can only ever have 1 instance in the context of the application
geggleto
  • 2,605
  • 1
  • 15
  • 18