Execute PHP function asynchronously

16

Using PHP, is it possible to perform a function asynchronously?

Example:

The client makes a request to the server, in this request PHP executes an asynchronous function that can take a few seconds, but before it finishes, the server responds to the client so that while the asynchronous operation is being executed , the browser does not have to wait until it stops responding.

    
asked by anonymous 01.08.2014 / 13:51

3 answers

8

Yes, from some external libraries you can implement similar things quite simply.

The most well-known project is reactPHP .

There is a very interesting benchmark comparing the reactPHP with nodeJS .

    
01.08.2014 / 13:57
4

You can achieve this result by using parallelism with the PHP Gearman

Example:

<?php
# Criação do worker
$gmworker= new GearmanWorker();

# Adicionando um servidor (localhost é o padrão)
$gmworker->addServer();

# Registre uma função
$gmworker->addFunction("reverse", "reverse_fn");

print "Esperando resultado...\n";

while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  } else {
    print "Ainda esperando resultado...\n";
  }
}

function reverse_fn($job)
{
  return strrev($job->workload());
}

See more examples in the PHP manual.

    
01.08.2014 / 13:57
3

In complento the two answers above, you can use German + reactPhp  with the gearman-async : "The Async Gearman implementation for PHP ontop of reactphp"

Example usage:

<?php

use Gearman\Async\ClientInterface;
use Gearman\Async\Event\TaskDataEvent;
use Gearman\Async\TaskInterface;
use Gearman\Async\Factory;

require_once __DIR__ . "/../vendor/autoload.php";

// use default options
$factory = new Factory();

$factory->createClient("127.0.0.1", 4730)->then(
    // on successful creation
    function (ClientInterface $client) {
        $client->submit("reverse", "Hallo Welt!")->then(function(TaskInterface $task) {
            printf("Submitted: %s with \"%s\" [handle: %s]\n", 
                $task->getFunction(), 
                $task->getWorkload(), 
                $task->getHandle()
            );

            $task->on('complete', function (TaskDataEvent $event, ClientInterface $client) {
                echo "Result: {$event->getData()}\n";
                $client->disconnect();
            });
        });
    },
    // error-handler
    function($error) {
        echo "Error: $error\n";
    }
);

$factory->getEventLoop()->run();
    
01.08.2014 / 21:26