Caching variables in PHP

2019-01-24 14:50发布

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.

标签: php caching
4条回答
Emotional °昔
2楼-- · 2019-01-24 15:26

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.

查看更多
神经病院院长
3楼-- · 2019-01-24 15:26

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.

查看更多
干净又极端
4楼-- · 2019-01-24 15:37

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

查看更多
女痞
5楼-- · 2019-01-24 15:41

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));
查看更多
登录 后发表回答