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 info开发者_运维知识库rmation 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:
- In a file on the file system
- Using
APC
which is an in memory local cache memcached
which is an in memory cache accessed over TCP/IP
For 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 (with unserialize()
).
I would probably go with APC
as by installing it you can easily benefit from it's opcode caching which is another function it can perform.
PHP doesn't do caching between sessions. You'll want to use one of the extensions that PHP has to do your caching. Some options include APC or Memcache. With either of these you can create your data, serialize it, and then set/get the data from the cache.
Have you looked into Drupal Variables?
http://drupal.org/project/drupal_variables
This will let you store values that you need access to all over the site. It sounds like what you are trying to store is either a large object or multi-faceted array, so I would store it either json_encoded or using php's serialize function. You will be able to access it from any module on the site, and to use it, you simply decode it in whatever function you used to store it.
精彩评论