Singleton Implementation in PHP

What we are trying to achieve is a Singleton which would hold an id to be generated for the master records. This Singleton would need to be persisted throughout various Apache/PHP processes and access to it will need to be synchronized (maybe using semaphores?) because it might need to be accessed by more than one process.

It’s important to remember that if PHP is configured as CGI, instances would be lost on each invocation. PHP would be invoked for each http request.

If PHP is configured as a module, then there would be multiple processes handling PHP requests. So, the instance would survive in "that particular" process. But subsequent requests might be handled by a different process.

We can pretty much assume that in our case PHP will configured as a module.

What are some of the suggested way to persist the data? Some of the feasible options might be serializing the singleton class and persisting it in the DB or a session variable?

Any thoughts or pointers would be much appreciated. Any specifics related to Yii in this particular case?

Interesting requirement and more interesting would be the design of your implementation.

Indeed, you cannot do a simple implementation in code since even if PHP is run as an Apache module (prefork), then each request will have its own singleton. Not too useful… :slight_smile:

if memcache, a popular daemon with PHP extension to connect to it, has decent locking capabilities, i would have considered it. DB can be useful as well back its performance lacks in comparison to memcache (although DB would have needed locking capabilities - just check that a lock can be "auto cleared" after some timeout by server if locking process is "gone").

If the last comment about locking details is not available in your DB, maybe consider implementing a simple command line PHP process for your need.

Have a look at the APC extension,