Run PHP function asynchronously

Asked

Viewed 6,637 times

18

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

Example:

The client(browser) makes a request to the server, in this request PHP executes an asynchronous function that may 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 need to wait for it to end to receive a response.

  • 1

    Did any of the answers help you? Or are there problems with them? Comment informing the author who doubts to try to use the proposed solution. If any of the answers solved your problem, mark it as correct by clicking on

  • PHP 7 already supports asynchronous programming.

3 answers

9


Yes, from some external libraries it is possible to implement similar things quite simply.

The best known project is the reactPHP.

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

  • 2

    Work In Progress I will summarize some points of the benchmark and insert the comparison charts when I’m at home

  • Where does the information come from that the reactPHP is the best known?

  • https://packagist.org/packages/react/react - A total of 22,000 installations downloaded by Packagist. If you know of one that goes beyond it, let me know.

  • But this only includes Composer packages. PHP extensions stay out of this count, right? Only one of the Bundles for SF2 interact with German has more than 11K

  • Gearman is a Jobs worker, he aims to "unblock" requests from the main server (example: incoming emails), asynchronous function is something else.

  • I await your summary

  • Calm :) Let’s see what I will learn from this question here before hehehe

Show 2 more comments

4

You can get this result using parallelism with the PHP extension 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());
}

Behold more examples in the PHP manual.

3

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

Example of use:

<?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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.