我已经学习PHP大约一个月了,我通过创建我的第一个真正的项目来测试我所学到的技能。我计划在MVC结构中从头做起(我知道使用像Laravel这样的框架会是一个更好的选择,但我想了解在我进入它们之前,框架会使事情变得更容易)。
然而,我在我的项目中遇到了困难,我非常希望得到一些建议。监视API变化的最佳方法是什么?例如,假设我想监视Stackoverflow API:http://api.stackexchange.com/2.2/info?site=stackoverflow。如果它从33个新的活动用户变为34个,我希望能够检测到这种变化。一旦它改变了,我希望它立即通知用户(我的“通知”指的是一个引导提醒div,它被推送给用户,而他们不需要刷新页面)。
目前我知道的唯一方法是使用cURL和cron作业,但是我觉得有更好的方法来完成这个任务,我想避免使用crons,因为我觉得检查后的一分钟间隔可能不够快。此外,多个用户可能会同时这么做--我已经注意到,crons可能会对我的小型VPS造成相当大的负担。
尽管告诉我,我在PHP中这么做是个白痴。如果有一种更适合这类工作的语言/框架(也许是Node?),我很想听听它。我可以搁置这个项目,直到我了解你们推荐什么,并选择一个完全不同的项目来做PHP。
发布于 2014-07-18 04:33:51
好吧,在PHP里你几乎被卷发/cron缠住了.但是您可以在客户机中使用一些ajax,我将使用jQuery,因为它很容易;)
在你的应用程序的页脚上(我想你会在所有页面中包含一个页脚)
<!-- make sure jQuery is included before this!! -->
<script type="text/javascript">
jQuery(document).ready(function($){
//we'll create an interval to poll the API..
setInterval(function(){
//do a POST to your cURL script...
$.post('http://website.com/curl.php',{ doCurl:true },function(resp){
//resp is an object ... { numUsers:SOMENUMBER }
//say you have a div somewhere on the page to display this number...could be hidden.......
if(resp.numUsers != parseInt($('#api-users').html())){
//display your popup..or whatever..
}
//load the div with the returned number..
$('#api-users').html(resp.numUsers);
},'json');
},1000); //runs every second...
});
</script>
curl.php
<?php
if(isset($_POST['doCurl'])){
//do the curl request to get the number...
$ch = curl_init('http://api.stackexchange.com/2.2/info?site=stackoverflow');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$curlout = curl_exec($ch);
curl_close($ch);
if($curlout){
$out = json_decode($curlout,true); //decode into array
$resp['numUsers'] = $out['items'][0]['new_active_users'];
}else{
$resp['numUsers'] = 0;
}
exit(json_encode($resp));
}
?>
那应该就行了!请记住,1秒是相当频繁的,可能更好的5秒,但这应该可以让您开始,否则耶节点,或使用tomcat(java)服务器将更适合服务器到客户端通信.
https://stackoverflow.com/questions/24817094
复制相似问题