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?






Loading....