7

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.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
AKor
  • 8,550
  • 27
  • 82
  • 136
  • possible duplicate of [Writing simple caching system in PHP](http://stackoverflow.com/questions/5658815/writing-simple-caching-system-in-php) and numerous others – Your Common Sense Apr 14 '11 at 06:51
  • Can you clarify your question? If you already have a cache mechanism, what's the problem? – Emil Vikström Apr 14 '11 at 06:51
  • unless the site is huge, and poorly written (slow) any speed increases will be negligible. –  Apr 14 '11 at 06:54

4 Answers4

12

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.

JohnP
  • 49,507
  • 13
  • 108
  • 140
3

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...

gd1
  • 11,300
  • 7
  • 49
  • 88
1

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));
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
1

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.

user228395
  • 1,156
  • 1
  • 11
  • 25