PHP code example of jenner / async-http-php

1. Go to this page and download the library: Download jenner/async-http-php 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/ */

    

jenner / async-http-php example snippets


$async = new \Jenner\Http\Async();
$task = \Jenner\Http\Task::createGet("http://www.baidu.com");
$async->attach($task, "baidu");

$task2 = \Jenner\Http\Task::createGet("http://www.sina.com");
$async->attach($task2, "sina");

$task3 = \Jenner\Http\Task::createGet("http://www.qq.com");
$async->attach($task3, "qq");

/**
 * you can do something here before receive the http responses
 * eg. query data from mysql or redis.
 */
 
$async-start();

while(true){
    // nonblock
    if(!$async->isDone()){
        echo "I am running" . PHP_EOL;
        sleep(1);
        continue;
    }

    $result = $async->execute();
    print_r($result);
    break;
}

/**
 * or you just call execute. it will block the process until all tasks are done.
 * $result = $async->execute();
 * print_r($result);
 */

$async = new \Jenner\Http\Async();
$task = \Jenner\Http\Task::createGet("http://www.baidu.com");
$promise = $async->attach($task, "baidu");

$promise->then(
    function ($data) {
        echo 'success:' . var_export($data, true) . PHP_EOL;
    },
    function ($data) {
        echo 'error:' . var_export($data, true) . PHP_EOL;
    }
);

$async->execute();
shell
[root@huyanping async-http-php]# php tests/performance_sync.php  
------------------------------------------
mark:[total diff]
time:55.121547937393s
memory_real:1536KB
memory_emalloc:1300.5859375KB
memory_peak_real:2304KB
memory_peak_emalloc:1898.640625KB
[root@huyanping async-http-php]# php tests/performance_async.php 
------------------------------------------
mark:[total diff]
time:4.6412570476532s
memory_real:256KB
memory_emalloc:187.7109375KB
memory_peak_real:13312KB
memory_peak_emalloc:10387.8671875KB