Okay, I wondered over that one for a while when I first started my career. Implemented it different ways and came up with two reasons to choose not to use static classes, but they are pretty big ones. One is that you will find that very often something that you are absolutely sure that you'll never have more than one instance of, you eventually have a second.
You may end up with a second monitor, a second database, a second server--whatever. When this happens, if you have used a static class you're in for a much worse refactor than if you had used a singleton. A singleton is an iffy pattern in itself, but it converts fairly easily to an intelligent factory pattern--can even be converted to use dependency injection without too much trouble.
For instance, if your singleton is gotten through getInstance(), you can pretty easily change that to getInstance(databaseName) and allow for multiple databases--no other code changes. The second issue is testing (And honestly, this is the same as the first issue). Sometimes you want to replace your database with a mock database.In effect this is a second instance of the database object.
This is much harder to do with static classes than it is with a singleton, you only have to mock out the getInstance() method, not every single method in a static class (which in some languages can be very difficult). It really comes down to habits--and when people say "Globals" are bad, they have very good reasons to say so, but it may not always be obvious until you've hit the problem yourself. The best thing you can do is ask (like you did) then make a choice and observe the ramifications of your decision.
Having the knowledge to interpret your code's evolution over time is much more important than doing it right in the first place.
The code that would call getInstance should have the instance(s) injected into it by the client code, and so shouldn't need to call getInstance in the first place. – Will Vousden Jan 4 at 23:49 1 @Will Vousden Correct, it's kind of a stop-gap.It's not really DI, but it can be pretty close. For instance, what if it was getInstance(supportedDatabase) and the instance returned was calculated based on which database was passed in?
The point is to avoid scaring people with a DI framework until they are ready for it. – Bill K Jan 5 at 1:08.
Singletons have very little - if not to say no - use in PHP. In languages where objects live in shared memory, Singletons can be used to keep memory usage low. Instead of creating two objects, you reference an existing instance from the globally shared application memory.In PHP there is no such application memory.
A Singleton created in one Request lives for exactly that request. A Singleton created in another Request done at the same time is still a completely different instance. Thus, one of the two main purposes of a Singleton is not applicable here.
The other purpose would be to have a global access point to an instance within the same Request. While this might sound desirable, it really isnt, because it creates coupling to the global scope (like any globals and statics). This makes Unit-Testing harder and your application in general less maintainable.
There is ways to mitigate this, but in general, if you need to have the same instance in many classes, use Dependency Injection. See my slides for Singletons in PHP - Why they are bad and how you can eliminate them from your applications for additional information. Even Erich Gamma, one of the Singleton pattern's inventors, doubts this pattern nowadays: "I'm in favor of dropping Singleton.
Its use is almost always a design smell" Further reading How is testing Registry Pattern or Singleton hard in PHP? What are the disadvantages of using a PHP database class as singleton? Database abstraction class design question Would Singleton be a good design pattern for a microblogging site?
Modifying a class to encapsulate instead of inherit How to access an object from another class? Why Singletons have no use in PHP The Clean Code Talks - Singletons and Global State If, after the above, you still need help deciding.
1. This is an example where the OP picks the wrong answer – yes123 May 10 at 18:02 +1. Great answer, Gordon!
– romaninsh May 21 at 21:13 Does this still apply when running under an FCGI daemon like PHP-FPM? – Gordon Jul 21 at 21:42 @Gordon yes. And even if it was possible to maintain objects between requests, Singletons still violate a couple SOLID principles and introduce Global State.
– Gordon Jul 22 at 6:49 I'm going to have to completely disagree on this one.... I have plenty of pages on my websites that multiple calls to different tables in the same database. If each page has an average of 6 connections and I can bring it down to 2 using this pattern, that's two-thirds saved. When you have high traffic, that is a significant saving.
And storing data in the $_SESSION can adverse affects as well. I'm not saying that you SHOULD use the Singleton, but there are cases it is much more desirable than dependency injection where you use yet another parameter. – Levi Morrison Oct 4 at 1:46.
Singletons are considered by many to be anti-patterns as they're really just glorified global variables. In practice there are relatively few scenarios where it's necessary for a class to have only one instance; usually it's just that one instance is sufficient, in which case implementing it as a singleton is completely unnecessary. To answer the question, you're right that singletons are overkill here.
A simple variable or function will do. A better (more robust) approach, however, would be to use dependency injection to remove the need for global variables altogether.
But Singletons can degrade very smoothly into DI, static classes cannot, which is the real problem with static classes. – Bill K Jan 4 at 16:53 @Bill: Very true, but then that's why I'd advocate a DI approach to begin with, rather than loose functions or static methods :) – Will Vousden Jan 4 at 16:55 In some languages (such as Java) static classes (or static methods of classes) can't be extended. So you create potential problems (or at best, more work) for future developers.So some suggest that static methods should be generally avoided unless you have a specific need for them.
– Marvo Jan 4 at 17:43.
In your example you're dealing with a single piece of seemingly unchanging information. For this example a Singleton would be overkill and just using a static function in a class will do just fine. More thoughts: You might be experiencing a case of implementing patterns for the sake of patterns and your gut is telling you "no, you don't have to" for the reasons you spelled out.
BUT: We have no idea of the size and scope of your project. If this is simple code, perhaps throw away, that isn't likely to need to change then yes, go ahead and use static members. But, if you think that your project might need to scale or be prepped for maintenance coding down the road then, yes, you might want to use the Singleton pattern.
Wow, just plain wrong. The whole point of the difference (the answer to the question) is how much harder it is to later fix your code to add a second instance. It is much harder to do that if you used static methods.
This is like saying "Globals are fine under your limited conditions" when the entire problem with Globals is that conditions change. – Bill K Jan 4 at 18:14 @Bill K: I agree with you and I would use a singleton if there was any complexity at all. But I was trying to answer the question from the OP's point of view and thought, well, yeah, I guess it is overkill in this very limited case.
Of course I was ignoring architectural or scalability concerns and a ton of other considerations. Should I have included that as a caveat in my answer aloing with a explanation on why someone should always use a singleton... which certainly would have caused downvotes from others? – Paul Sasik Jan 4 at 18:33 I guess I'm concerned with the number of upvotes you got--It indicates that there are a lot of people who really don't understand software engineering and that what's really critical are not the problems you are trying to solve, but how to help the NEXT guy fix your implementation with the least amount of fuss.
– Bill K Jan 4 at 21:04 @ Bill: I know, it is a gray-area and people tend to go one way or the other. For example, there's a school of thought where a singleton is actually considered an anti-pattern or code smell. Then some tend to apply patterns everywhere, all the time.
Honestly, when I posted this answer I figured that i'd either get a bunch of upvotes or a bunch of downvotes. – Paul Sasik Jan 4 at 21:22.
Your interpretation is correct. Singletons have their place but are overused. Often, accessing static member functions is sufficient (notably, when you do not need to control time-of-construction in any way).
Better, you can just put some free functions and variables in a namespace.
First, I just want to say that I don't find much uses to the Singleton pattern. Why would one want to keep a single object thorough the whole application? Especially for databases, what if I want to connect to another database server?
I have to disconnect and reconnect every time...? Anyway... There are several drawbacks to using globals in an application (which is what the traditional use of the Singleton pattern does): Difficult to unit test Dependency injection issues Can create locking issues (multi-threaded application) Use static classes instead of a singleton instance provides some of the same drawbacks as well, because the biggest problem of singleton is the static getInstance method. You can limit the number of instances a class can have without using the traditional getInstance method: class Single { static private $_instance = false; public function __construct() { if (self::$_instance) throw new RuntimeException('An instance of '. __CLASS__.' already exists'); self::$_instance = true; } private function __clone() { throw new RuntimeException('Cannot clone a singleton class'); } public function __destruct() { self::$_instance = false; } } $a = new Single; $b = new Single; // error $b = clone($a); // error unset($a); $b = new Single; // works This will help on the first the points mentioned above: unit testing and dependency injection; while still making sure a single instance of the class exist in your application.
You could, per example, just pass the resulting object to your models (MVC pattern) for them to use.
Consider simply how your solution differs from the one presented in the PHP docs. In fact, there is just one "small" difference: your solution provides callers of the getter with a PDO instance, while the one in the docs provides callers of Database::singleton with a Database instance (they then use the getter on that to get a PDO instance). So what conclusion do we reach?
In the documentation code, callers get a Database instance. The Database class may expose (in fact, it should expose if you 're going to all this trouble) a richer or higher-level interface than the PDO object it wraps. If you change your implementation to return another (richer) type than PDO, then the two implementations are equivalent.
There's no gain to be had from following the manual implementation. On the practical side, Singleton is a pretty controversial pattern. This is mainly because: It's overused.
Novice programmers grok Singleton much easier than they grok other patterns. They then go on to apply their newfound knowledge everywhere, even if the problem at hand can be solved better without Singleton (when you 're holding a hammer, everything looks like a nail). Depending on the programming language, implementing a Singleton in an airtight, non-leaky manner can prove to be a titanic task (especially if we have advanced scenarios: a singleton depending on another singleton, singletons that can be destroyed and re-created, etc).
Just try to search for "the definitive" Singleton implementation in C++, I dare you (I own Andrei Alexandrescu's groundbreaking Modern C++ Design, which documents much of the mess). It imposes additional workload both when coding the Singleton and when writing code to access it, workload which you can do without by following a few self-imposed constraints on what you try to do with your program variables. So, as a final conclusion: your singleton is just fine.
Not using Singleton at all is just fine most of the time as well.
I don't see any point to this at all. If you implemented the class in such a way that the connection string was taken as a parameter to the constructor and maintained a list of PDO objects(one for eaah unique connection strign) then maybe there would be some benefit, but the implementation of singleton in this instance seems like a pointless excersise.
You are not missing anything, as far as I can see, the example is pretty flawed. It would make difference, if the singleton class had some non static instance variables.
When programming there is not "right" and "wrong"; there is "good practice" and "bad practice". Singletons are generally created as a class to be reused later. They need to be created in such a way that the programmer doesn't accidentally instantiate two instances while drunkenly coding at midnight.
If you have a simple little class that shouldn't be instantiated more than once, you don't need to make it a singleton. It's just a safety net if you do. It's not always bad practice to have global objects.
If you know that you're going to use it globally/everywhere/all the time, it may be one of the few exceptions. However, globals are generally considered "bad practice" in the same way that goto is considered bad practice.
Php - Who needs singletons. Singletons is need by (without quotes):. Singletons was need by (without quotes):.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.