Singleton question

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
janusmccarthy
Forum Newbie
Posts: 8
Joined: Fri Apr 10, 2009 5:11 pm

Singleton question

Post 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?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Singleton question

Post 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.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Singleton question

Post by jackpf »

Surely if your constructor is private "new" wouldn't work though...
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Singleton question

Post by Darhazer »

Show your code.
What you are refer "a static in-class singleton pattern" and "external helper method" to?
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Singleton question

Post by josh »

PHP does not have singletons, you have to emulate it. Private constructors will enforce usage of your static factory method
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Re: Singleton question

Post by Jenk »

private constructors raise recoverable errors, not fatal ones, so ensure error logging is enabled.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Singleton question

Post by jackpf »

I thought private caused a fatal error. Protected causes recoverable.
Post Reply