Amp是一个PHP非阻塞并发框架,它提供了一个事件循环,promise 和stream作为异步编程的基础。与生成器结合使用的promise用于构建协程,它允许像同步代码一样编写异步代码,而不需要任何回调。
demo:
<?phpuseAmp\Artax\Respose;useAmp\Loop;require__DIR__.'/../vedor/autoload.php';Loop::ru(fuctio(){$uris=["https://google.com/","https://github.com/","https://stackoverflow.com/",];$cliet=ewAmp\Artax\DefaultCliet;$cliet->setOptio(Amp\Artax\Cliet::OP_DISCARD_BODY,true);try{foreach($urisas$uri){$promises[$uri]=$cliet->request($uri);}$resposes=yield$promises;foreach($resposesas$uri=>$respose){prit$uri."-".$respose->getStatus().$respose->getReaso().PHP_EOL;}}catch(Amp\Artax\HttpExceptio$error){//IfsomethiggoeswrogAmpwillthrowtheexceptiowherethepromisewasyielded.//TheCliet::request()methoditselfwilleverthrowdirectly,butretursapromise.prit$error->getMessage().PHP_EOL;}});
评论