|
|||||||||||||||
Current Texts Comic Imprint Calendar Search PHP-Classes Container-Wizard main.s21 |
|||||||||||||||
Categories
{{login}}
|
Paranoid Singleton
I did some reading on the Singleton-Pattern, including drastic warnings what would befall me if I should ever use it. So another minefield on the map of Information Technology. Actually, I haven't used Singleton for seven years except in one short lived exception; when I was more into OOP, I used Registry instead. I mainly follow the reasoning of the Anti-Singleton-Movement; as someone of IBM put it, Singleton pulls a value out of thin air without being immediately visible within, say a method signature. And I really hate it when things are pulled out of thin air, especially if you cannot "ensure beyond paranoid doubt" that it will actually be there. However, I've seen worse - wide abuse of constants or global values, and, especially evil, global arrays of, say, configuration parameters. Moving them into classes is certainly less evil, and realizing said classes as Singleton might be appropriate in some cases. The usual Singleton blueprint for PHP usually looks like that:
<?php
This common definition has a drawback. When using Singleton, you will most likely have two different uses. Instantiating the Singleton for the first time, give some information to it, like configuration. The second is when you instantiate it again, somewhere deep within your application, to actually use the Singleton. However, when calling Singleton::getInstance(), you can never be sure whether you get the very first instance or another one. And I'm of the opinion that it is reasonable to force the coder to know what he is doing, having him distinguish between "first" and "further" calls of getInstance:
<?php
If the Singleton is wrongly created, the programmer gets what he deserves (and what he needs): an Exception telling him what is wrong and where. CommentsPlease note: comments posted won't be visible immediately, as they will be checked for harmful content. |