我已经学习PHP大约一个月了,我正在通过创建我的第一个真正的项目来测试我学到的技能。我计划在MVC结构中从头开始做所有事情(我知道使用像Laravel这样的框架会是一个更好的选择,但我想了解框架在我跳进它们之前使事情变得多么容易)。
然而,我的项目遇到了瓶颈,如果你能给我一些建议,我将非常感激。观察API变化的最好方法是什么?例如,假设我想监视Stackoverflow信息API: http://api.stackexchange.com/2.2/info?site=stackoverflow。如果它从33个新的活跃用户变为34个,我希望能够检测到这种变化。一旦它改变了,我希望它能立即通知用户(通过通知,我只是指一个Bootstrap警告div,推送给用户,而不需要刷新页面)。
目前我所知道的唯一方法是使用cURL和cron作业,但我觉得有更好的方法来实现这一点,我希望避免使用cron,因为我觉得检查后的一分钟间隔时间不够快。此外,多个用户可能同时执行此操作-我注意到crons对我的小型VPS来说非常繁重。
请随意告诉我,我在PHP中这样做是一个白痴。如果有一种语言/框架更适合这种类型的工作(也许是Node?),我很乐意听到它。我可以暂时搁置这个项目,直到我知道你们的建议,并选择一个完全不同的项目来做PHP
好吧,在PHP中你几乎被cURL/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)服务器将更适合服务器到客户端通信…