开发者

How to Variable Cache in PHP

开发者 https://www.devze.com 2023-03-28 00:58 出处:网络
I am looking at trying to cache variables in PH开发者_StackOverflow中文版P from a JSON file. Is there anyone that knows of a good tutorial or can provide an example?Save variable to file cache:

I am looking at trying to cache variables in PH开发者_StackOverflow中文版P from a JSON file. Is there anyone that knows of a good tutorial or can provide an example?


Save variable to file cache:

file_put_contents('cache.txt', json_encode($variable));

Read cache into variable:

$variable = json_decode(file_get_contents('cache.txt'));


Memcached is your best bet. It will save any serializable data in a very fast cache. You can find a tutorial at:

http://php.net/manual/en/memcache.examples-overview.php

It is lightning quick and has many other features that makes it better than just saving a txt file to the server.

$memcache->set('key', $jsonstring, false, 10)

and

$get_result = $memcache->get('key');


A simple approach is:

function getMyJson()
{
    $data = apc_fetch('my_json', $wasCached);
    if ($wasCached) {
        return $data;
    }
    $data = json_decode(file_get_contents('/path/to/data.json'));
    apc_store('my_json', $data);
    return $data;
}

This uses APC's cache but you could work similarly with memcached, redis etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号