PHP code example of calabashdoll / curl-future
1. Go to this page and download the library: Download calabashdoll/curl-future library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
calabashdoll / curl-future example snippets
/**
* 获得一个延迟执行curl的类
* @param $url 请求url地址
* @param $options = array(),
* header:头信息(Array),
* proxy_url:代理服务器地址,
* timeout:超时时间,可以小于1
* post_data: string|array post数据
* @return CurlFuture\HttpFuture
*/
function curl_future($url, $options = array());
echo curl_future("http://s.newhua.com/2015/1113/304528.shtml?4", array())
->fetch();
$f4 = curl_future("http://s.newhua.com/2015/1113/304528.shtml?4");
$f5 = curl_future("http://s.newhua.com/2015/1113/304528.shtml?5");
echo strlen($f1->fetch()); //这个地方会并行执行
echo "\n";
echo strlen($f2->fetch());
echo "\n";
echo curl_future("http://s.newhua.com/2015/1113/304528.shtml")
->then(function($data){
return strlen($data);
})
->then(function($len){
return "Length: $len";
})
->fetch();
class BookModel{
//接口串行调用的示例,通过then函数将处理过程串联起来
static public function getTitleFuture($id){
return curl_future("http://111.202.7.252/{$id}")
->then(function($data){
return strlen($data);
})
->then(function($data){
$url = "http://111.202.7.252/{$data}";
$html = curl_future($url)->fetch();
preg_match('/title(.+?)\/title/is', $html, $matches);
return $matches[1];
});
}
//普通接口调用+后续处理的示例
static public function getContentFuture($id){
return curl_future("http://111.202.7.252/{$id}")
->then(function($data){
return substr($data, 0, 100);
});
}
}
//多个请求并行发出示例,这个地方用Model封装起来,便于和不同框架相结合
$t1 = BookModel::getTitleFuture('111');
$t2 = BookModel::getTitleFuture('222');
$t3 = BookModel::getTitleFuture('333');
$c1 = BookModel::getContentFuture('111');
$c2 = BookModel::getContentFuture('222');
$c3 = BookModel::getContentFuture('333');
//fetch函数会阻塞住,这个地方会把所有队列里面的请求发出,直到需要获取的t1的请求执行完再返回
var_dump($t1->fetch());
//由于上个fetch已经阻塞过了,下面的这个fetch很可能无需阻塞直接返回,也有可能上面的fetch没有执行完,此处阻塞住继续执行请求,直到拿到t2的数据
var_dump($t2->fetch());
var_dump($c3->fetch());
//task_manager.php
public function fetch($ch){
$chKey = (int)$ch;
//如果两个队列里面都没有,那么退出
if(!array_key_exists($chKey, $this->runningTasks) && !array_key_exists($chKey, $this->finishedTasks) )return false;
$active = 1;
do{
//如果任务完成了,那么退出
if(array_key_exists($chKey, $this->finishedTasks))break;
//执行multiLoop,直到该任务完成
$active = $this->multiLoop();
//如果执行出错,那么停止循环
if($active === false)break;
}while(1);
return $this->finishTask($ch);
}