PHP code example of jaxwilko / weird-php

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

    

jaxwilko / weird-php example snippets


use Weird\Promise;

Promise::make(function (Thread $thread) {
    // do some really cool stuff
    $result = 'Hello world';
    return $result;
})
    ->then(function (string $result) {
        echo $result;
        // Prints: Hello World
    })
    ->catch(function (\Throwable $e) {
        // This will catch any exceptions happening parent process, not the child process.
    })

use Weird\ProcessManager;
use Weird\Processes\Thread;
use Weird\Promise;

$manager = ProcessManager::create()
    ->spawn(Thread::class, processes: 1);

$manager->dispatch([
    // Promise 1
    Promise::make(function () {
        return 'hello';
    })->then(fn ($str) => $str . ' world')
        ->then(fn ($str) => echo $str . PHP_EOL),

    // Promise 2
    Promise::make(function () {
        return 'world';
    })->then(fn ($str) => $str . ' hello')
        ->then(fn ($str) => echo $str . PHP_EOL)
]);

$manager = ProcessManager::create()
    ->withBootstrap(__DIR__ . '/vendor/autoload.php')
    ->spawn(Thread::class);

$manager = ProcessManager::create()
    ->spawn(Thread::class, processes: 1);

$manager->dispatch(function () {
    // do something
});

$manager->wait(timeout: 0.5);

$manager = ProcessManager::create()
    ->spawn(Thread::class, processes: 1);

$manager->dispatch(
    Promise::make(function () {
        // do something
    })->then(function (string $output) {
        // do something else
    })
);

while ($doingSomethingElse) {
    // ...
    $manager->tick();
    // ...
}

$manager->registerHintHandler(function (mixed $message, Process $process) {
    echo $message;
});

$manager->registerUnknownMessageHandler(function (mixed $message, Process $process) {
    echo $message;
});

class MyCustomProcess extends \Weird\Processes\ParallelProcess
{
    // Define how often tick should be executed in seconds
    protected float $tickRate = 1 / 32;

    public function register()
    {
        // execute startup tasks
    }

    public function read($stdin)
    {
        while ($message = $this->readStream($stdin)) {
            // do something with messages sent from the parent process
        }
    }

    public function tick()
    {
        // do something
    }
}

// ...

$manager = ProcessManager::create()
    ->spawn(MyCustomProcess::class, processes: 5);
bash
composer