Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function after returning response

I have an API created with Slim 3.

In it I have some curl execution such as sending Push notification to a user.

I want send response to requester then execute curl or any other function.

I read about Threads in PHP and use pthreads-polyfill but it sends response after finishing Thread.

Sample tested code:

 $app->get('/test', function (Request $request, Response $response) {
    PushController::publish("1111111", "HELLO");
    $result =  'OK';

    return $response->getBody()->write($result)->withStatus(200);
});
like image 410
MohammadReza Vahedi Avatar asked Feb 23 '26 18:02

MohammadReza Vahedi


2 Answers

I understand what you are trying to do, and threading is not the answer. One solution is to call a script from the main one, as you mentioned. A more elegant one imho, is to call fastcgi_finish_request . It will return the answer to the requester and continue to execute the script. Unfortunately this function is only available with PHP-FPM. Which is the industry standard by now but does not necessarily comes as default when you install a LAMP stack.

like image 113
JesusTheHun Avatar answered Feb 26 '26 09:02

JesusTheHun


For your requirement two solutions may suite

  1. Queue
  2. Cron

Redis can be used as queuing server. For that you need to install redis server on your system. There is php implementation of predis for Redis. For more details about Redis you can read it in Redis official site. Beanstalkd can also used as Queuing server.

To learn, how to create cron jobs you can refer the exisitng stackoverflow question

like image 34
Sathishkumar Rakkiyasamy Avatar answered Feb 26 '26 07:02

Sathishkumar Rakkiyasamy