Caching variables in PHP
I've been caching the output buffer of pages lately, but now I want to cache the values of variables.
I have a PHP file that does a bunch of MySQL queries, then fills variables with various data from those queries.
Some of those variables will never change but some will change quite often. How can I cache开发者_开发问答 certain variables in this manner? I'm using file-based caching, if it helps.
Yup, file based caching is an option.
There are also other options like memcache and APC
You should have a look at these as well. If your application is putting a lot of load on your MySQL server, and if your DB is already optimized, caching is a step you can take.
You can dump any variable (including an array) using serialize, and the inverse is unserialize.
Dumping to a file would be quite a useless cache solution, you can consider using memcache which can store any variable in memory, but requires some work on server side.
I find that a local mysql with MEMORY tables can be useful, too...
I dont know, how you structured your current caching stuff, so this is just a short template on how you can save any kind of variable (as long as its content is serializeable) to a file.
file_put_contents($filename, serialize($variable));
Since you asked about file-based caching, both memcache
and APC
are no option, although I would certainly recommend both in cases where the stored data is not too large.
For file based caching, I would recommend you to use a caching framework. For example, you could use Zend_Cache
from the Zend Framework
. It allows you to store your query results in files by using a nice object oriented interface. Plus, you've got a lot of options, such as validation and serialization. There are also other caching frameworks out there.
精彩评论