, , 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();
}
API- twitter , 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) {
$this->db = $db;
$this->url = $url;
$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()
{
$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()
{
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;
$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+, - .
, , . try/catch PDO (: - , URL-, blob ..).
, .
[edit] ( ) . github. , , - ajax ( jQuery),
$.ajax({
url: "http://example.com/twitter.php",
type: "get",
data: {url: "http://stackoverflow.com"}
success: function(data, textStatus, jqXHR) {
console.log(data);
}
});