3. Why do we need it?
●
To reduce the number or retrieval queries
made to a database
●
To reduce the number of requests made to
external services
●
To reduce the time spent computing data
●
To reduce filesystem access
4. A basic example
●
A Post
● 23 comments
● Sidebar Contents
●
Navigations
● Categories
● Much more...
We have to load -
5. 1. Check if already cached
if(the resource is cached) {
Just display it.
}
// TOP of your script
$cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
// Serve from the cache if exist
if (file_exists($cachefile)) {
include($cachefile);
exit;
}
6. 2. Generate content and cache
else{
Get the resource, Display it and Cache.
}
ob_start(); // start the output buffer
// – Your normal PHP script and HTML content here –
// BOTTOM of your script
// save the contents of output buffer to the file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush(); // Send the output to the browser
7. 3. Expire the cache
●
Event/Trigger
●
Setting a time
if(new comment || post edited) {
Expire cache for this post
}
$cachetime = 120 * 60; // 2 hours
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile)
&& (time() - $cachetime < filemtime($cachefile))) {
include($cachefile);
Exit;
}
8. So, It was simple. right?
Request
Output
Cache
Compute
Miss
Hit
Store
1
2
3
4
Request
9. Your question is ...
My pages always have an ever changing content
and cannot be cached in their entirety
12. What to cache?
Anything that...
● you don't want to fetch or compute every time your code runs.
● isn't going to change very often
To find them, monitor
● Queries
● Page loads
● Web Analytics
16. A Quick Benchmark
PHP Native PHP w/APC
Concurrency Level 10
Time taken for tests 60 seconds
Complete requests 298 914
Total transferred 643,149 bytes 1,962,675 bytes
HTML transferred 516,971 bytes 1,582,035 bytes
Requests per second 4.91 [#/sec] 15.21 [#/sec]
Time per request 2035.405 [ms] 657.623 [ms]
Time per request
(mean, across all concurrent requests)
203.541 [ms] 65.762 [ms]
Transfer rate 10.35 [KB/s] received 31.88 [KB/s] received