0

Implementing the Singleton Design Pattern in PHP

One of the features I miss most about ColdFusion when I'm working in PHP is the application scope.  It's so easy to take it for granted, but it really does make life easier to have that layer of shared scope.  I'm currently working on a PHP application that requires authentication.  Not a unique problem, right?  I mean, so many applications require authentication.  Alas.

In my head, this need begs for an AuthenticationService object to provide the mechanism.  There's no reason I can conceive of that this shouldn't be a singleton, but how do I store it?  As far as I know, my only options in PHP are a file-based data store or a database.

I don't care much for either of those options, so I'm considering a pragmatic deviation from the pure solution.  Rather than incur the overhead and potential risk of file IO or database access, I think I might create my, ahem, singleton and store it in each user's $_SESSION scope.  It's no longer a "true" singleton, but I think that the overhead of creating the service instance once for each session is likely to be smaller than the other options.

Anyone have any better ideas?  Am I unaware of a feature of PHP that might offer a better solution? 

tags:
Development
 
Let me start by saying nothing about PHP... but is there any concept of a Server scope?

Could you populate a Server.{ApplicationName} type of structure?
 
posted 855 days ago
Add Comment Reply to: this comment OR this thread
 
 
Sadly, there is not. PHP has no instance of itself in memory. A new PHP instance is started with each web session (which is why, if I'm stating that correctly, there's no application or server shared scope layer).

Just one of the features I miss, but there are others it has - although the number got significantly reduced with CF8.
 
posted 855 days ago
Add Comment Reply to: this comment OR this thread
 

Search

Rob  Wilkerson