Leverage swoole_ Process and EventLoop for PHP asynchronous programming

Time:2021-7-28

The idea is simple:

Start a child process to process asynchronous transactions. After processing, tell the parent process through the pipeline and write the returned data to the pipeline

The code is as follows:

AsynHttpClient.php

<?php 

class AsynHttpClient
{
    public $url;

    public $callback;

    private $process;

    public function __construct($url, $callback) 
    {
        $this->url = $url;
        $this->callback = $callback;
        $this->run();
    }

    public function run()
    {
        $this->process = new swoole_process([$this, "callback"], true); 
        $this->process->start();
        swoole_event_add($this->process->pipe, function($pipe) {
            $content = $this->process->read();
            call_user_func($this->callback, $content);
            swoole_event_del($this->process->pipe);
        });
    }

    public function callback(swoole_process $process)
    {
        $ch = curl_init($this->url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $content = curl_exec($ch);

        curl_close($ch);
        
        $process->write($content);
    }
}

index.php

require 'AsynHttpClient.php';

new AsynHttpClient("http://127.0.0.1:9000/api.php", function($data) {
   print_r($data);
});

echo 1;

api.php

<?php 

echo json_encode([
  'state' => 'ok',
  'data' => 'hello',
]);
php -S 127.0.0.1:9000

You can see that the running result is 1, which proves that it is executed asynchronously

In fact, through pcntl in PHP_ Fork and libevent can also be implemented without the help of swoole, but the process provided by swoole is really easy to use

https://www.iwantmoney.cn/art…