Amp是一个PHP非阻塞并发框架,它提供了一个事件循环,promise 和stream作为异步编程的基础。与生成器结合使用的promise用于构建协程,它允许像同步代码一样编写异步代码,而不需要任何回调。
demo:
<?phpuseAmp\Artax\Response;useAmp\Loop;require__DIR__.'/../vendor/autoload.php';Loop::run(function(){$uris=["https://google.com/","https://github.com/","https://stackoverflow.com/",];$client=newAmp\Artax\DefaultClient;$client->setOption(Amp\Artax\Client::OP_DISCARD_BODY,true);try{foreach($urisas$uri){$promises[$uri]=$client->request($uri);}$responses=yield$promises;foreach($responsesas$uri=>$response){print$uri."-".$response->getStatus().$response->getReason().PHP_EOL;}}catch(Amp\Artax\HttpException$error){//IfsomethinggoeswrongAmpwillthrowtheexceptionwherethepromisewasyielded.//TheClient::request()methoditselfwillneverthrowdirectly,butreturnsapromise.print$error->getMessage().PHP_EOL;}});
评论