The Little Guy Posted September 20, 2012 Share Posted September 20, 2012 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! Quote Link to comment https://forums.phpfreaks.com/topic/268611-singleton-design-patterns/ Share on other sites More sharing options...
shlumph Posted September 20, 2012 Share Posted September 20, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/268611-singleton-design-patterns/#findComment-1379643 Share on other sites More sharing options...
KevinM1 Posted September 20, 2012 Share Posted September 20, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/268611-singleton-design-patterns/#findComment-1379644 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.