检索缓存
One way to make your website exponentially faster is by caching both remote and internal requests. Why request your RSS subscriber count from FeedBurner more than once a day if that count is calculated once per day? Why hit your database on each page load if that content rarely changes? I've created a primitive request-and-cache function for PHP that checks for fresh content in the cache and retrieves content from a source if fresh content isn't available.
使您的网站成倍增长的一种方法是通过缓存远程和内部请求。 如果每天计算一次,为什么要每天从FeedBurner请求您的RSS订阅者计数不止一次? 如果该内容很少更改,为什么要在每次页面加载时命中数据库? 我为PHP创建了一个原始的请求和缓存功能,该功能检查缓存中的新鲜内容,如果没有新鲜内容,则从源中检索内容。
PHP功能 (The PHP Function)
/* gets the contents of a file if it exists, otherwise grabs and caches */function get_content($file,$url,$hours = 24,$fn = '',$fn_args = '') { //vars $current_time = time(); $expire_time = $hours * 60 * 60; $file_time = filemtime($file); //decisions, decisions if(file_exists($file) && ($current_time - $expire_time < $file_time)) { //echo 'returning from cached file'; return file_get_contents($file); } else { $content = get_url($url); if($fn) { $content = $fn($content,$fn_args); } $content.= '
My get_content function accepts four arguments:
我的get_content函数接受四个参数:
- The file to grab content from. If the file doesn't exist, the file is created and content placed into. 从中获取内容的文件。 如果文件不存在,则创建文件并将内容放入其中。
- The URL to get content from if cached content isn't fresh. 如果缓存的内容不新鲜,则从中获取内容的URL。
- A function name to pass the freshly received content to. 将新接收的内容传递到的函数名称。
- Arguments to pass to the third argument's function. 传递给第三个参数的函数的参数。
The function is, of course, very primitive. I like that my function handles both retrieval and caching so that I don't need to repeat code whenever I want cached content.
该功能当然非常原始。 我喜欢我的函数既处理检索又处理缓存,这样我就不需要在需要缓存内容时重复代码。
样品用法1 (Sample Usage 1)
/* usage */$TWITTER_FOLLOWERS_FILE_NAME = 'twitter-followers.txt';$TWITTER_FOLLOWERS_URL = 'http://twitter.com/users/show.json?screen_name=davidwalshblog';$TWITTER_FOLLOWERS = get_content($TWITTER_FOLLOWERS_FILE_NAME,$TWITTER_FOLLOWERS_URL,3,'format_followers',array('file'=>$TWITTER_FOLLOWERS_FILE_NAME));/* utility function */function format_followers($content,$args) { $content = json_decode($content); $twitter_subscribers = $content->{'followers_count'}; if($twitter_subscribers) { $twitter_subscribers = number_format($twitter_subscribers,0,'',','); file_put_contents($args['file'],$twitter_subscribers); return $twitter_subscribers; }}
The above code retrieves my Twitter follower count, parses the code, and caches the content for three hours.
上面的代码检索我的Twitter关注者数量,解析代码,并将内容缓存三个小时。
There are several more advanced PHP caching classes available but the simple function above covers most of my needs -- hopefully it can help you out too!
有几个更高级PHP缓存类可用,但是上面的简单函数可以满足我的大部分需求-希望它也可以为您提供帮助!
翻译自:
检索缓存