3

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);
});
Masoud Mokhtari
  • 2,390
  • 1
  • 17
  • 45
  • 1
    I don't know if there is way to do it after the response (AFAIK no). I always use a third party queue service, like Amazon SQS or RabbitMQ for that purpose – Pipe Feb 12 '18 at 14:14
  • 1
    Try to use either Queue jobs or CRON jobs. CRON jobs are simpler to implement. Redis can be used to implement queuing system. – Sathishkumar Rakkiyasamy Feb 12 '18 at 14:14

2 Answers2

1

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.

JesusTheHun
  • 1,217
  • 1
  • 10
  • 19
1

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

Sathishkumar Rakkiyasamy
  • 3,509
  • 2
  • 30
  • 34