Possible duplicate:
Who needs singletones?
I was wondering what are the disadvantages of using singletones in php scripts. I use a lot of them, and sometimes I do not understand the criticisms of the developers. Some examples:
I have a Request class:
Sanitizing POST, GET, COOKIE inputdata and using it instead of global arrays - strictly and globally. how
$request = Request::getInstance(); $firstname = $request->post('firstname', $additionalFilters);
There is always only one request per request. Why is using a singleton a bad idea in this case?
Same thing for $ _SESSION:
I have a Session (Singleton) class that represents an $ _SESSION array, because there is only one session, and I use it globally.
Database
$mysql = DB::getInstance('mysql', 'dbname'); //pseudo $sqlite = DB::getInstance('sqlite', 'dbname'); //pseudo
For each type of database, I want only one object and never again. In my opinion, there is a risk of chaos.
Unique strings
Also, I often use classes to represent / use a unique row of the db table.
$article = Article::getInstance($id); $navigation = Navigation::getInstance($id);
I see only the benefits of doing it this way. I never want the second object to represent a unique string. Why is there such a bad idea here?
In fact, most (almost all) of my classes do not have a common constructor, but always a static method such as getInstance ($ id) or create (), so the class itself handles possible instances (which does not mean that they are, by definition, all singleton)
So my question is: are there any flaws that I have not yet understood. And what is the specific scenario that singleton doubters think of when advised against singleton.
Edit:
Now you have a singleton that wraps around $ _POST, but what if you don't have $ _POST but want to use the file instead for input? In this case, it would be more convenient if you had an abstract input class and create an instance of POSTInput to control input through published data.
Good, real benefits. I did not realize this. This is especially true for the Request class.
Nevertheless, I have doubts about this approach. Suppose I have a "Functionality" class that performs a specific request (for example, a guestbook component). Inside this class I want to get the passed parameter. So I get an instance of Singleton request
$req = Request::getInstance(); $message = $req->post('message');
Thus, only my functional object takes care of the Request class.
When I use the non-element approach, I need to somehow create an additional class / function to control that each request receives a valid request object. Thus, my Functionality class does not need to know about this control class, but, in my opinion, there is still a dependency / problem: every time I create a Functionality object object, there is a chance that I forget to set the request object.
Of course, I can define an optional parameter when creating functionality. But this leads to some redundant parameter for some time. Or not?