PHP code example of stephanschuler / fork-job-runner

1. Go to this page and download the library: Download stephanschuler/fork-job-runner 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/ */

    

stephanschuler / fork-job-runner example snippets



declare(strict_types=1);

namespace StephanSchuler\Demo;

use StephanSchuler\ForkJobRunner\Utility\WriteBack;
use StephanSchuler\ForkJobRunner\Job;

class DemoJob implements Job
{
    public function run(WriteBack $writeBack): void
    {
        // Do something
    }
}


declare(strict_types=1);

namespace StephanSchuler\Demo;

use StephanSchuler\ForkJobRunner\Dispatcher;

$dispatcher = Dispatcher::create(
    \escapeshellcmd(\PHP_BINARY) . ' ' . \escapeshellarg(\__DIR__ . '/loop.php')
);

$dispatcher->run(
    new DemoJob()
);


declare(strict_types=1);

use StephanSchuler\ForkJobRunner\Dispatcher;
use StephanSchuler\ForkJobRunner\Loop;



declare(strict_types=1);

use StephanSchuler\ForkJobRunner\Utility\WriteBack;
use StephanSchuler\ForkJobRunner\Dispatcher;
use StephanSchuler\ForkJobRunner\Job;
use StephanSchuler\ForkJobRunner\Response;

class DemoJob implements Job
{
    public function run(WriteBack $writer) : void
    {
        $writer->send(
            new Response\DefaultResponse('this goes to stdout')
        );
        $writer->send(
            new Response\ThrowableResponse(
                new RuntimeException('This is an exception')
            )
        );
        throw new RuntimeException('This is another exception');
    }
}

assert($dispatcher instanceof Dispatcher);

$job = new DemoJob();
$responses = $dispatcher->run($job);

foreach ($responses as $response) {
    switch (true) {
        case ($response instanceof Response\NoOpResponse):
            // No Op responses act as keep alive signal.
            // There is at least two per job, one at the beginning and one 
            // at the end.
            break;
        case ($response instanceof Response\DefaultResponse):
            // Default responses contain text.
            // They are not used internally.
            \fputs(\STDOUT, $response->get());
            break;
        case ($response instanceof Response\ThrowableResponse):
            // This catches both,
            // the explicite call of $writer->send()
            // as well as the thrown exception.
            \fputs(\STDERR, print_r($response->get(), true));
            break;
       case ($response instanceof Response\Response):
            // Feel free to implement custom responses.
            break;
    }
}