Page 1 of 1

Singleton question

Posted: Wed Sep 16, 2009 2:02 pm
by janusmccarthy
Hello there!

I've managed to inherit some code for a small plugin for tiny_mce. In cleaning it up, I added a logging feature and I discovered that a particular php object was created multiple times from different scripts. There was no need for a new instance of the object each time, and I thought a singleton design pattern may be more appropriate.

So I changed the class to use a singleton design pattern (I used a static in-class singleton pattern rather than an external helper method like the one at: http://www.ibm.com/developerworks/libra ... signptrns/), but kept the log messages to know when new was being called and which script created it. I ensured that the constructor was private, and that calling classes used the pattern.

I ran the program and ensured it ran as expected.

Then I checked the logs, I *expected* that there would be one call where the object would be created, and everything else would get the information from the static variable.

Instead, based on the logs, the scripts are STILL creating this object everywhere.

So my question is: When SHOULD a new singleton get created? What is its scope?

Re: Singleton question

Posted: Wed Sep 16, 2009 3:28 pm
by superdezign
The singleton design pattern does not support the use of the "new" keyword. I suspect that you are using it though, if you are creating the object.

Re: Singleton question

Posted: Wed Sep 16, 2009 3:33 pm
by jackpf
Surely if your constructor is private "new" wouldn't work though...

Re: Singleton question

Posted: Wed Sep 16, 2009 3:55 pm
by Darhazer
Show your code.
What you are refer "a static in-class singleton pattern" and "external helper method" to?

Re: Singleton question

Posted: Thu Sep 17, 2009 10:18 pm
by josh
PHP does not have singletons, you have to emulate it. Private constructors will enforce usage of your static factory method

Re: Singleton question

Posted: Fri Sep 18, 2009 6:08 am
by Jenk
private constructors raise recoverable errors, not fatal ones, so ensure error logging is enabled.

Re: Singleton question

Posted: Fri Sep 18, 2009 7:20 am
by jackpf
I thought private caused a fatal error. Protected causes recoverable.