Jump to content

Recommended Posts

Are singleton design patterns a good or bad idea? Can I get some extra input on why you guys think about singletons?

 

I just read this, on how to make a singleton:

http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html

 

So any additional feedback would be great!

Link to comment
https://forums.phpfreaks.com/topic/268611-singleton-design-patterns/
Share on other sites

The Singleton pattern is considered an anti-pattern now by most programmers. Static creation makes it difficult to test and, if suddenly the class doesn't need to be a singleton anymore, requires lots of changes.

 

Dependency injection is the way to go instead.  Leaving the object creation strategy to a Dependency injection container makes it easy to inject mock version of the dependencies and test classes under isolation.  And with DI, you can still maintain a single instance of the class.

They're generally a bad idea.  They're an anti-pattern - something that looks good initially, but quickly makes one's code harder to maintain.  By design they're global, which blows apart encapsulation.  The standard examples of a db connection or config file reader/registry/whatever tend to miss the point.  In PHP (and other languages), objects are passed by reference (in PHP a reference is technically just an alias, but it acts about 99% like a real reference for our use).  This means that composition and argument passing is cheap in terms of memory management.  Multiple objects can hold a shared reference to another without much of a penalty.  And since most base application resources (db connections, config data) are created/loaded before the app does real work, there's generally no reason why they can't be passed into the objects that need them.  So, one bootstrapped db connection can be passed around to the many objects that require it.

 

That's essentially what Dependency Injection is, and it's why it's a far better alternative.  Just about anywhere you see someone suggest a Singleton for web programming, what they really should do is implement DI to make their lives easier without blowing apart encapsulation and scope.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.