使您的网站速度呈指数级增长的一种方法是缓存远程和内部请求。如果计数每天计算一次,为什么还要每天多次从 FeedBurner 请求 RSS 订阅者计数?如果内容很少更改,为什么要在每次页面加载时访问您的数据库?我为 PHP 创建了一个原始的请求和缓存函数,用于检查缓存中的新内容并在新内容不可用时从源检索内容。
PHP 函数
/* 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.= ''; file_put_contents($file,$content); //echo 'retrieved fresh from '.$url.':: '.$content; return $content; } } /* gets content from a URL via curl */ function get_url($url) { $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5); $content = curl_exec($ch); curl_close($ch); return $content; }
我的 get_content 函数接受四个参数:
- 要从中获取内容的文件。如果文件不存在,则创建文件并将内容放入其中。
- 如果缓存的内容不新鲜,则从中获取内容的 URL。
- 要传递的函数名称新收到的内容。
- 要传递给第三个参数的函数的参数。
当然,该功能非常原始。我喜欢我的函数处理检索和缓存,这样我就不需要在需要缓存内容时重复代码。
示例用法 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; } }
以上代码检索我的 Twitter 关注者数量,解析代码,并将内容缓存三个小时。
有几个更高级的 PHP 缓存类可用,但上面的简单功能满足了我的大部分需求——希望它也能帮助您!