Phil Sturgeon写了关于基准测试的article。
我所关注的是这项名为ReactPHP的技术。
我去过他们的GitHub,但是如果没有一个例子,我仍然不能把它包裹起来。
谢天谢地,我可以使用Phil的回购。
第12行,Phil用ReactPHP创建了一个循环。
https://github.com/philsturgeon/nonblockingbro/blob/master/p2-async.php#L12
然后他开始在第24行使用循环
https://github.com/philsturgeon/nonblockingbro/blob/master/p2-async.php#L24
我的问题是:
$loop
的目的是什么? 我正在努力了解这项技术,所以如果我的问题措辞严重,请告诉我,以便我可以重写。
修改
由于我收到的回答是问题太广泛,所以让我缩小我的问题,并将其引用到代码示例中。
从https://github.com/philsturgeon/nonblockingbro/blob/master/p2-async.php#L12获取代码示例,
我在下面重复了一遍。 $loop
做了什么?
$loop = React\EventLoop\Factory::create();
$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dnsResolver = $dnsResolverFactory->createCached('8.8.8.8', $loop);
$factory = new React\HttpClient\Factory();
$client = $factory->create($loop, $dnsResolver);
echo "Page number, Time taken";
for ($page = 1; $page <= $total_page; $page++) {
$loop->addTimer(0.001, function($timer) use ($client, $page) {
$buffer = '';
$request = $client->request('GET', 'http://fantasy.premierleague.com/my-leagues/303/standings/?ls-page='.$page);
$request->on('response', function($response) use (&$buffer) {
$response->on('data', function($data) use (&$buffer) {
$buffer .= $data;
});
});
$request->on('end', function() use (&$buffer, $page) {
\phpQuery::newDocument($buffer);
foreach (pq('.ismStandingsTable tr') as $data) {
foreach (pq('td', $data) as $key => $val) {
if ($key == 2) {
// print pq($val)->text();
}
}
}
$time_end = microtime(true);
$execution_time = $time_end - $GLOBALS['time_start'];
echo ("\n".$page.", ".$execution_time);
});
$request->end();
});
}
$loop->run();
答案 0 :(得分:3)
1 - 这个$循环的目的是什么?
好吧,$ loop var用于将所有closures functions保存到一个数组中,以便稍后异步执行。
2 - 它在ReactPHP上说,它是一个简单的Web服务器。这是否意味着它取代了nginx或Apache?
ReactPHP不会替换或与(Apache2 | Nginx)对抗,它会在大多数情况下将一些问题汇总到CLI进程。
3 - 何时是使用ReactPHP或任何类似技术的好时机?什么时候不是使用它的好时机?
我真的不在生产服务器上使用ReactPHP,但是它已经非常成功地执行一些自动批处理或测试登台服务器中的一些问题。
答案 1 :(得分:0)
The loop does exactly what it says. It loops. Just like node.js it continuously repeats the infinte cycle and waits for some states of attached tasks to change. These changes emit events that can be handled exactly as the occur. This gives you the opportunity to react to external events (another process in your os, another Webservice or likewise). This is called reactive programming.
Possible use cases are socket servers (w/o ngjnx or Apache) that wait for clients to connect (e.g. webchat) or saving current stock prices from stock exchange that you are connected to via a socket connection.