Question on Singleton

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
SwizzCodes
Forum Newbie
Posts: 20
Joined: Tue Dec 19, 2006 3:23 pm

Question on Singleton

Post by SwizzCodes »

Hi all,

ok so this is all about the singleton pattern. I find it pretty usefull, but I often read, that singletons are anti-patterns and they are no good use for OOP because they sprinkle dependencies all over the place in my programm. Still, I find myself using this pattern quite often. I wrap it around database connections, sessions, user-objects, Error-message-collectors, Input-Controllers and so on. So what do you think, is this good practice? Or what should I use instead?

cya
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Instead of creating a bunch of singletons, you may want to look into creating a class which stores each instance of each class that you create. This way you can minimize memory usage while at the same time have access to a bunch of classes without having to code them all as singletons.
SwizzCodes
Forum Newbie
Posts: 20
Joined: Tue Dec 19, 2006 3:23 pm

Post by SwizzCodes »

oh, good idea. so that would be a singleton-registry which holds one instance per class that I use, right ? hmm why didn't I thought of this in the first place :)
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

not necessarily one instance per class.
SwizzCodes
Forum Newbie
Posts: 20
Joined: Tue Dec 19, 2006 3:23 pm

Post by SwizzCodes »

that's right, but I probably want to, since I use it to replace my singletons.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

You also might want to look through the long list you provided to see if it is:

1. Actually possible for you code to create multiple instances improperly. Often programmers implement Singletons to protect against use cases that don't exist.

2. Possible to inject those objects into the objects that use them rather than accessing them as a global. The injection could be directly or via a Registry.
(#10850)
Post Reply