views:

134

answers:

2

Hello,

We have a need to access a DB that only allows one connection at a time. This screams "singleton" to me. The catch of course is that the singleton connection will be exposed (either directly or indirectly) via a web-service (most probable a SOAP based web-service - located on a separate server from the calling app(s) ) - which means that there may be more than one app / instance attempting to connect to the singleton class.

In PHP, what is the best way to create a global singleton or a web-service singleton?

TIA

+3  A: 

In PHP, there is no such thing as a "global" object that resides across all requests . In a java webserver, this would be called "application level data store". In php, the extent of the "global" scope (using the global keyword) is a single request. Now, there is also a cross session data store accessible via $_SESSION, but I'm trying to highlight that no variable in php is truly "global". Individual values emulate being global by being stored to a local file, or to a database, but for something like a resource, you are stuck creating it on each request.

Now, at the request level, you can create a Singleton that will return an initialized resource no matter which scope within the request you call it from, but again, that resource will not persist across or between requests. I know, it is a shortcoming of php, but on the other hand, the speed and stability of the individual requests help make up for this shortcoming. Edit: After reading over your question again, I realized you may not be asking for a singleton database access class, but rather something that can resource lock your database? Based on what you said, it sounds like the database may do the locking for you anyway. In other words, it won't allow you to connect if there is already another connection. If that is the case, it seems kind of like you have 2 options: 1) just let all your pages contend for the resource, and fail if they don't get it.

2) Create a queue service that can accept queries, run them, then cache the results for you for later retrieval.

Zak
thanks for the note... As mentioned below, maybe we'll have to write a daemon for this. I'm surprised there aren't any 3rd party solutions for this sort of thing...
ChronoFish
Thanks Zak. Yes you are correct. The DB only allows single access at a time. We've discussed using a queue and are leaning that way. Thank you for reinforcing the idea.
ChronoFish
+4  A: 

This screams "use a DB SERVER" to me. ;-), but...

You could create an SoapServer and use a semaphore to allow only 1 connection at a time

$s1 = sem_get(123, 1);
sem_acquire($s1);

// soapserver code here

sem_release($s1); 
Bob Fanger
When hooking into 3rd party apps you rarely get to dictate architecture. Clearly a proper DB server is the way to go when that is a possibility. Thank for the semaphore reminder. Maybe we'll have to write a daemon.....
ChronoFish