PHP code example of publicplan / parallel-bridge

1. Go to this page and download the library: Download publicplan/parallel-bridge 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/ */

    

publicplan / parallel-bridge example snippets


// app/config/worker-bootstrap.php


declare(strict_types=1);

use App\Kernel;
use Symfony\Component\Dotenv\Dotenv;

set_time_limit(0);

if (class_exists(Dotenv::class)) {
    if (method_exists(Dotenv::class, 'bootenv')) {
        (new Dotenv())->bootEnv(dirname(__DIR__) . '/.env');
    } else {
        

// src/Service/YourClass.php


declare(strict_types=1);

namespace App\Service;

use Amp\MultiReasonException;
use Publicplan\ParallelBridge\PromiseWaitInterface;

class YourClass
{
    /** @var PromiseWaitInterface */
    private $promiseWait;

    public function __construct(PromiseWaitInterface $promiseWait)
    {
        $this->promiseWait = $promiseWait;
    }

    public function yourFunction(): void
    {
        $unprocessDataArray = range(1, 100);

        try{
            //If we want to use a container class it must be public and in the following format:
            $finalDataArray = $this->promiseWait->parallelMap($unprocessDataArray, [$this,'processSingleElement']);
        } 
        //to get possible errors you have to catch MultiReasonException 
        catch (MultiReasonException $exception ){
            dd($exception);
        }
        print_r($finalDataArray);
    }

    //This Function will be called async from our processes after grabbing this service from service container
    public function processSingleElement(int $number): string
    {
        for ($i = 0; $i < 200000; $i++) {
         $hash =  hash('SHA512', (string)$number);
        }
        return $hash;
    }
}



declare(strict_types=1);

namespace App\Service;

use Publicplan\ParallelBridge\PromiseWaitInterface;

class YourClass
{
    /** @var PromiseWaitInterface */
    private $promiseWait;

    public function __construct(PromiseWaitInterface $promiseWait)
    {
        $this->promiseWait = $promiseWait;
    }
    
    public function yourFunction(): void
    {
        $unprocessDataArray = range(1, 100);
        $additionalArg = 42;

        $result = $this->promiseWait->parallelMap(
           $unprocessDataArray, 
           [$this,'processSingleElement'],
           $additionalArg,
        );
        
        //Returns numbers from 43 to 143
        print_r($result);
    }

    public function processSingleElement(int $number, int $additionalArg): int
    {
        return $number + $additionalArg;
    }
}