473,395 Members | 1,647 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Singletons in PHP

I was reading an article on TalkPHP (http://www.talkphp.com/
showthread.php?t=1304) about singletons but I'm afraid I don't
understand why I need to use them. I understand how to code them
perfectly, it's just the theory I'm having some problems with. I did
try searching on Wikipedia but it didn't yield any satisfactory
reasoning, for me.

Could someone explain it to me in basic terms, please. I initially
came across singletons when I was looking for ways in which to save on
the extra memory of instantiating many of the same objects, and if I
am right, a singleton would do just that? I'm just not sure how as it
looks fairly straightforward in its implementation.

Thanks in advance.
Nov 30 '07 #1
7 1779
I was reading an article on TalkPHP (http://www.talkphp.com/
showthread.php?t=1304) about singletons but I'm afraid I don't
understand why I need to use them. I understand how to code them
perfectly, it's just the theory I'm having some problems with. I did
try searching on Wikipedia but it didn't yield any satisfactory
reasoning, for me.
As with so many things, you don't really NEED them. Singletons are (or
are often abused as) global variables: You never know when these objects
are constructed, and have very little control over it. When it comes to
unit testing, they can be a real pain in, you know where.
The main problem is that they do not abide the Law of Demeter: they do
not come in through the interface of your objects.
Could someone explain it to me in basic terms, please. I initially
came across singletons when I was looking for ways in which to save on
the extra memory of instantiating many of the same objects, and if I
am right, a singleton would do just that? I'm just not sure how as it
looks fairly straightforward in its implementation.
It is not the memory usage, I think. It is more that you would want only
one instance of an object with a "uniqueness guarantee". Like you do not
want two error logs to overwrite each other if they have taken the
filename from the same setting. You can, off course, put such an
instance on an Application object as well. It is a matter of taste.

Best regards,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Nov 30 '07 #2
>I was reading an article on TalkPHP (http://www.talkphp.com/
>showthread.php?t=1304) about singletons but I'm afraid I don't
understand why I need to use them. I understand how to code them
perfectly, it's just the theory I'm having some problems with. I did
try searching on Wikipedia but it didn't yield any satisfactory
reasoning, for me.

Could someone explain it to me in basic terms, please. I initially
came across singletons when I was looking for ways in which to save on
the extra memory of instantiating many of the same objects, and if I
am right, a singleton would do just that? I'm just not sure how as it
looks fairly straightforward in its implementation.
A singleton is based on the assumption that there is only one of
something, and you can represent that something with an object.
For example, if you want to represent pressing THE key on THE
keyboard with THE finger, you can use singletons for key, keyboard,
and finger. IMHO, such an assumption is usually silly. There's
only one database? Nonsense, I've had several pages which used 3
databases on 3 different servers (the purpose was to test data
migration before actually switching over to the new system).

Dec 1 '07 #3
ad*************@gmail.com wrote:
I was reading an article on TalkPHP (http://www.talkphp.com/
showthread.php?t=1304) about singletons but I'm afraid I don't
understand why I need to use them. I understand how to code them
perfectly, it's just the theory I'm having some problems with. I did
try searching on Wikipedia but it didn't yield any satisfactory
reasoning, for me.

Could someone explain it to me in basic terms, please. I initially
came across singletons when I was looking for ways in which to save on
the extra memory of instantiating many of the same objects, and if I
am right, a singleton would do just that? I'm just not sure how as it
looks fairly straightforward in its implementation.

Thanks in advance.
A singleton is basically where you have a single object in the script.

For instance - I use singletons a lot when working with databases.

To keep it simple - let's say I have a database. I have objects
representing each table in the database (not really, but we're keeping
it simple).

Now, on any one page I may need to access 1 table, 5 tables, or anything
in between. I could create a database object on the page itself and
pass it to each of the table objects, but that means I need to keep
track of the database in each of my pages.

Alternatively, I could get a database object for each table, but that
would mean multiple connections in a single script.

Or, I could create a singleton object, and have each of the tables use
that singleton. The web page script doesn't have to worry about it (in
fact it doesn't even know about the database). And I don't have
multiple connections to the database.

Does this help?

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================

Dec 1 '07 #4
"Willem Bogaerts" <w.********@kratz.maardanzonderditstuk.nlwrote in
message news:47*********************@news.xs4all.nl...
As with so many things, you don't really NEED them. Singletons are (or
are often abused as) global variables: You never know when these objects
are constructed, and have very little control over it. When it comes to
unit testing, they can be a real pain in, you know where.
The main problem is that they do not abide the Law of Demeter: they do
not come in through the interface of your objects.
Willem - could you explain that last sentence, please?
Dec 3 '07 #5
>The main problem is that they do not abide the Law of Demeter: they do
>not come in through the interface of your objects.
Willem - could you explain that last sentence, please?
The Law of Demeter is a set of rules to reduce tight coupling in
object-oriented programs.

Passing the necessary related objects through the interface (methods,
constructor) ensures that your object stays modular. This has a few
advantages: they can be used in more general applications and (even
better) they can be tested with unit tests.

Suppose you have an object that references the Singleton "Database". You
would have a hard time to write a unit test that provides a mock
database or a test database object, because the object does not recieve
a database; it will locate that itself. And there is the problem. The
object is _hardwired_ to the Database object.

Or suppose you want the same object, but now for a different database.
You would have the same problem.

By the way, because of the amount of legacy code that I encountered that
were completely hardwired all around, I wrote a pattern to migrate the
use of such a Singleton to something more testable: the Half-a-Singleton
pattern (see http://www.w-p.dds.nl/pathalfs.php?STYLE=4)

I often draw an analogy of objects to electronic components: if you see
a wire welded from your CD drive to the speaker, for instance, they have
effectively become one component. If it is plugged, they are still
separate, but connected. The interface of an object is in a lot of ways
like a plug in hardware.

Best regards,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Dec 3 '07 #6
ad*************@gmail.com wrote:
I was reading an article on TalkPHP (http://www.talkphp.com/
showthread.php?t=1304) about singletons but I'm afraid I don't
understand why I need to use them. I understand how to code them
perfectly, it's just the theory I'm having some problems with. I did
try searching on Wikipedia but it didn't yield any satisfactory
reasoning, for me.

Could someone explain it to me in basic terms, please. I initially
came across singletons when I was looking for ways in which to save on
the extra memory of instantiating many of the same objects, and if I
am right, a singleton would do just that? I'm just not sure how as it
looks fairly straightforward in its implementation.

Thanks in advance.
I generally use singletons when parsing a page. I don't really need to
create different instacdes of an object, so I use a singletom. I could
achieve the same effect using a procedural style, but its easily to
mantain a class.
Dec 3 '07 #7

"Willem Bogaerts" <w.********@kratz.maardanzonderditstuk.nlwrote in
message news:47*********************@news.xs4all.nl...
>>The main problem is that they do not abide the Law of Demeter: they do
not come in through the interface of your objects.
>Willem - could you explain that last sentence, please?

The Law of Demeter is a set of rules to reduce tight coupling in
object-oriented programs.

Passing the necessary related objects through the interface (methods,
constructor) ensures that your object stays modular. This has a few
advantages: they can be used in more general applications and (even
better) they can be tested with unit tests.

Suppose you have an object that references the Singleton "Database". You
would have a hard time to write a unit test that provides a mock
database or a test database object, because the object does not recieve
a database; it will locate that itself. And there is the problem. The
object is _hardwired_ to the Database object.
not a good example. you assume we construct 'database' the same way you
would. a singleton is instanciated upon the first call to one of it's
interfaces. giving that interface a param, like a connection string, would
not only instanciate the object but let it connect and utilize a db.

i don't understand 'because the object does not receive a database'. a db
class SHOULD locate that itself, imo...that goes to encapsulation. in fact,
if you don't let the db class handle everything about the db to which it
communicates, you actually tightly couple some other facility to work in
conjunction with the db class.

again, not a good example.
Or suppose you want the same object, but now for a different database.
You would have the same problem.
no problem at all.

db::initialize('server name', 'db name', 'user', 'password',
dbTypes::mySql);

or you can name 'initialize' to 'connect'. dbTypes::mySql gives a namespace
to supported db types and is itself, a singleton.

your base db object and specific implementations implements a db interface
and, when you 'connect', your main db object creates a specific instance of
the db type you want. there's no problem there *at all*.
By the way, because of the amount of legacy code that I encountered that
were completely hardwired all around, I wrote a pattern to migrate the
use of such a Singleton to something more testable: the Half-a-Singleton
pattern (see http://www.w-p.dds.nl/pathalfs.php?STYLE=4)
interesting. singletons weren't actually supported in php < 5. there is a
way to mimic it in previous versions, but an upgrade and running a script
that uses the convention will quickly show you where the problem is...by
kindly blowing up. :)
I often draw an analogy of objects to electronic components: if you see
a wire welded from your CD drive to the speaker, for instance, they have
effectively become one component. If it is plugged, they are still
separate, but connected. The interface of an object is in a lot of ways
like a plug in hardware.
sorry willem, this just shows you haven't gotten your EE credentials. the
wire and the cd are seperate components. you may well need to replace either
one, however, replacing one doesn't require altering the other. finally,
it's called 'soldering'...not welding. and any less-than-dim person would
know to *solder* a connector to the wire and one to the cd drive...and yes,
the connectors are separate components.

an interface less like a plug in hardware than it is a tool in a swiss army
knife. :)
Dec 5 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: stephan beal | last post by:
Good morning, C++ users, i've been hesitating to post this, primarily because i know that most of you here are *way* ahead of me in C++ and i'm a little embarassed about the possibility of some...
11
by: Tito | last post by:
I have two questions about the singletons' chapter of Alexei Alexandrescu's "C++ Modern Design". 1. In the beginning of the chapter Alexei states that a "singleton" class implementation made of...
3
by: Dominik Rau | last post by:
Hi. I've got the following problem here: In my application, I use a lot of Singletons, that are implemented as described in Gamma et al. (shortened): //.h class Singleton{ public: static...
8
by: 6tc1 | last post by:
Hi all, I'm having a problem where in my solution that contains multiple projects - I instantiate a singleton class in one assembly and then if another assembly tries to use that singleton class...
11
by: John Fly | last post by:
I'm working on a large project(from scratch). The program is essentially a data file processor, the overall view is this: A data file is read in, validated and stored in a memory structure...
6
by: Steven Watanabe | last post by:
PEP 8 says, "Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators." I know that "is" is an identity operator, "==" and "!=" are the equality...
5
by: Omega | last post by:
I'm interested in seeing a bit of discussion about using singletons in ASP.NET 2.0. Currently I've designed a singleton that gets a reference to it's single instance stored inside the ASP.NET...
6
by: =?Utf-8?B?R29yZG8=?= | last post by:
Hello everyone, I've been trying for some time now to move to C++/CLI, but I have several large legacy C++ static libraries I need to use. When I set up a simple solution with a C++/CLI Winforms...
12
by: Craig Allen | last post by:
Hey, forgive me for just diving in, but I have a question I was thinking of asking on another list but it really is a general question so let me ask it here. It's about how to approach making...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.