好吧,正如我在评论中提到的,我会使用 Memcached 和一个数据库,但我会起草一个仅数据库的解决方案(使用 PDO 用于 twitter)并将 Memcached 部分作为奖励练习留给你。 ;)
我会通过 AJAX 加载关注者信息,以减少页面加载时间,例如关注者数量需要更新。
我将使用以下数据库架构:
CREATE TABLE IF NOT EXISTS `Followers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`url` varchar(100) NOT NULL,
`data` longtext NOT NULL,
`followers` int(5) NOT NULL,
`last_update` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
首先我要定义一个接口,这样你就不用依赖任何实现了:
interface SocialFollowers
{
public function getFollowers();
}
然后,对于 twitter 共享 API,我将有一个实现类,它获取数据库句柄和用于初始化的目标 URL。类属性由检索到的数据(如果可用)填充。如果时间戳足够新,您将立即获得关注者数量,否则会查询 API、存储结果并检索关注者数量。
class TwitterFollowers implements SocialFollowers
{
private $data = null;
private $url = "";
private $db = null;
private $followers = null;
protected $shareURL = "https://cdn.api.twitter.com/1/urls/count.json?url=";
public function __construct($db, $url) {
// initialize the database connection here
// or use an existing handle
$this->db = $db;
// store the url
$this->url = $url;
// fetch the record from the database
$stmt = $this->db->prepare('SELECT * FROM `Followers` WHERE url = :url ORDER BY last_update DESC LIMIT 1');
$stmt->bindParam(":url", $url);
$stmt->execute();
$this->data = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($this->data))
$this->followers = $this->data["followers"];
}
public function getFollowers()
{
// create a timestamp that's 30 minutes ago
// if it's newer than the value from the database -> call the api
$old = new DateTime();
$old->sub(new DateInterval("PT30M"));
if (is_null($this->followers) || (new DateTime($this->data["last_update"]) < $old) ) {
return $this->retrieveFromAPI();
}
return $this->followers;
}
private function retrieveFromAPI()
{
// mostly untouched
ob_start();
$twittershare = $this->shareURL . $this->url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $twittershare);
curl_setopt($ch, CURLOPT_HEADER, 0);
$jsonstring = curl_exec($ch);
curl_close($ch);
$bufferstr = ob_get_contents();
ob_end_clean();
$json = json_decode($bufferstr);
$this->followers = $json->count;
// store the retrieved values in the database
$stmt = $this->db->prepare('INSERT INTO Followers (url, data, followers)'
.'VALUES (:url, :data, :followers)');
$stmt->execute(array(
":url" => $this->url,
":data" => $bufferstr,
":followers" => $this->followers
));
return $this->followers;
}
}
对于 Facebook、Google+、the-next-social-network,您只需添加另一个实现。
请注意,此代码未经测试。它错过了 PDO 查询的一些 try/catch 块,并且还有改进的空间(例如:缺少某种锁定机制来防止同时检索相同的 URL,是否有必要存储返回的 blob 等)。
希望对你有所帮助。
[编辑] 我稍微更新了代码(修复了一些拼写错误和转换问题)并对其进行了测试。您可以在github 找到工作版本。所缺少的只是像 ajax sn-p(假设是 jQuery)这样的
$.ajax({
url: "http://example.com/twitter.php",
type: "get",
data: {url: "http://stackoverflow.com"}
success: function(data, textStatus, jqXHR) {
// Update the corresponding counter like
// $("#twitterfollowers").text(data);
console.log(data);
}
});