I’m new to PHP and I’m having no luck googling for a best practice that targets this scenario.
I have a data structure that’s expensive to create, applies to all users of the site, is identical for all users of the site, and never changes once created. (OK — it needs to change whenever I upload new versions of source code files.) It’s not particularly large. Ideally, I’d like to create it one time — the first time I need it — and hold onto it thereafter, using the same instance for every user, every page request. Then it would be nice if it would get “nulled out” whenever I click “clear cached data” (I’m using Drupal).
I haven’t found a tutorial for how to do this… I see how I can store information in the session, but that only applies to one user.
UPDATE
Inside the data structure there are anonymous functions (closures). I have read that these sometimes have issues serializing.
It sounds what you’re looking for is some kind of cached object.
There a number of different caching methods you could use in PHP:
APCwhich is an in memory local cachememcachedwhich is an in memory cache accessed over TCP/IPFor each of these you’d likely want to serialize your data structure (with PHP’s
serialize()), save it to the cache store and then read it back and unserialize the data (withunserialize()).I would probably go with
APCas by installing it you can easily benefit from it’s opcode caching which is another function it can perform.