0

Does PHP has a built in fragment caching mechanism to server side cache code parts?

For example, I have a page that queries the database 15x times. Most times the results will be the same, even between users. Caching is a good option! These results are shown in HTML (with echo commands). It would be nice to cache the results of that code part. I cannot collect all the echo's in one variable. Is there a easy way to "record" the results of that php code with a begin and end, and save it in the cache?

Thanks!

Arjen
  • 289
  • 2
  • 4
  • 11
  • look at this: http://stackoverflow.com/questions/5659574/caching-variables-in-php – Black Sheep Sep 11 '13 at 20:30
  • Nothing "built in" that I'm aware of, but you could build something yourself, like write the results to a file using `file_put_contents` then use `filemtime` to see how old the results are? – naththedeveloper Sep 11 '13 at 20:32
  • if its on one page load, just realod the same data you already have in a variable. mysql will also do caching by default. –  Sep 11 '13 at 20:32
  • Uhm, I have to deal with a dynamic query (inside a loop). Therefore, output caching as a whole would be the most easiest. Thus, caching the generated HTML inside that code part (currently, I do that with an echo inside the loops). – Arjen Sep 11 '13 at 20:40

3 Answers3

0

As far as I know, PHP doesn't have a built in caching mechanism for fragments. You could manually cache fragments to physical files and check their modified datestamps every 5 minutes (or however long) and include them if they're "fresh". If not, you'd run your queries and write them to that cache file (or files).

Tim B
  • 1,879
  • 1
  • 13
  • 8
0

There are lots of options for web application caching. In your case I would look into

  • Caching pages or parts of pages in PHP. If the code isn't set up to make this easy, you could turn on output buffering, then take the buffer at some point and write it to disk.
  • Having your templates cache some or all of their output. Smarty, for example, has this built-in.
  • Shared memory caching of your results with memcache or APC (although that's deprecated in the latest version of PHP).
  • Caching in your database or normalizing some of your data so it's queried in a simpler, quicker fashion.
Matt S
  • 14,976
  • 6
  • 57
  • 76
  • Your first hint took me too [this](http://php.dzone.com/news/php-caching-pages-with-output-) article. Thanks! – Arjen Sep 12 '13 at 12:13
0

It's your responsibility to cache results of DB query, in any language.
Try to use Redis as a cache storage - it's very easy to use and has good PHP drivers.

OZ_
  • 12,492
  • 7
  • 50
  • 68