开发者

PHP variable caching

I have some data in MySQL database that are static most of the time. They are mainly almost static values like cities, states, and ethnic. I want to cache them in a variable, preferebly in memory, so that I won't need to perform another query to MySQL every time a page loads.

The problem is, my hosting doesn't support memcache nor APC. The only accelerator I could find is eAc开发者_如何学JAVAcelerator, and I don't think it will do what I have in mind.

Is there any way I can do caching? It is http://www.k-disk.net

Thank you


Caching is a great example of the ubiquitous time-space tradeoff in programming. You can save time by using space to store results. [1]

There are many ways at many levels to implement cache on a website. Lets look at them starting form the front end and moving towards the backend without getting into too much details.

HTTP caching

See How To Optimize Your Site With HTTP Caching

Application level caching

This is caching of "expensive to query" database objects. Eg: memcache, caching pages in files etc.

Op-code cache

Eg: PHP accelerator, eAccelerator etc.

Database level cache

Optimizing the database by tuning its parameters based on the need and machine hardware.

In your case, I would recommend tweaking around with my.cnf since given enough RAM, MySQL is quite fast. Just try not to pre-optimize.


You can use the Shared Memory extension.

Look this basic sample: http://www.php.net/manual/en/shmop.examples-basic.php


You could just write a file to your server that saves a serialized php array of variables. Just plug all of your variables into an associative array then serialize and save. Though I honestly don't see why you don't save the variables to a variable table in the database. Its not an expensive operation.

$myvars = array(
  'how_high_do_i_jump' => 10,
  'which_tv_show_is_best' => 'Glee',
  'enable_caching' => true,
  'mathematical_solution' => 4534.234
);

$file_str = serialize($myvars);

//Save the file
file_put_contents('myvars.ser', $myvars);

//To reverse just do this
$file = file_get_contents('myvars.ser');

$myvars = unserialize($file);

If that doesn't work for you there is a way to get memcache on your shared host if you have SSH access. I actually did this on hostmonster. Here is a walk through on it (though this is not the article I originally used).
http://andrewpeng.net/posts/2011/06/271273-memcached-and-dreamhost-shared-tutorial.html


You can create a custom cache class storing and reading data from disk, using file_put_contents() and file_get_contents().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜