|
Posted by Dikkie Dik on 11/21/29 11:30
More about singletons:
A singleton is a static class that has an accessor for exactly one
instance of the class. This is then the only instance that can be
created. There are a few drawbacks to this:
- If you ever need more than one object of that kind, you have a
problem. And if you write unit tests, you do have to create another
instance just for the test. Singletons are a real pain to test and don't
scale at all.
- The instance is not passed via the interface (= the publicly available
methods) of the class. Effectively, a singleton is a global read-only
variable that is set automatically. If you want to replace it (for
testing, for instance), you again have a problem.
The fact that the singleton is not passed through the interface
"hardwires" it to any place in the code where it is used. This obscures
the class dependencies in the code.
So where would I put the instance if I don't want a singleton? On a
small php page I could just use a plain non-object oriented variable. On
more complex applications, I have an object structure with some root
object that contains the data that is accessible within that section.
This root object is responsible for this data (either by checking the
input parameters of its constructor or by creating the necessary
instances itself).
Best regards
Daedalus.OS wrote:
> Ok first I'm pretty new to OOP, so my question may sound stupid to some of
> you. If the only answer you can provide is "get a book about OOP" then don't
> loose your time and mine cause it's already ordered. I'm just too curious
> about this one to wait for the book.
>
> I would like to know is if it's good php programming practice to use
> abstract classes instead of singleton classes. For exemple a login class.
> I've made one as an abstract class and now I'm wondering if it's a good
> idea. Technically there would be only one login object so I thought having
> this object was pointless and I use an abstract class with everything in it
> static. Is it a good or a bad idea and why? In what situation the difference
> between having only one object and no object at all with only static
> functions and variables would lead to use one more the other? Or why in a
> PHP context would I prefer to have a single object rather than what I would
> call a "static virtual object".
>
>
> Thanks,
> Dae
>
>
[Back to original message]
|