2

I have the following dilemma, I have a SOAP API, need to optimise a method:

public function myMethodForOptimisation(array $options) {
    //doing some stuff

    $this->requestsAnUltraSlowTimeConsumingMethod();

    return $someData;
}

I do not really need to wait for the finalisation of the $this->requestsAnUltraSlowTimeConsumingMethod() i just asynchronously want to say to this method to do stuff and return the result to customer.

Need to transform it in something like:

public function myMethodForOptimisation(array $options) {
    //doing some stuff

    async_method_call($this->requestsAnUltraSlowTimeConsumingMethod());

    return $someData;
}

Is there an async_method_call() in PHP ?

Alexandru Olaru
  • 6,842
  • 6
  • 27
  • 53
  • Threads or fork a cURL request. Either way you need a way of notifying your main application that the resource is available at some point. – Sergiu Paraschiv Feb 10 '15 at 13:14
  • But be aware that it will act different on different operating systems as well as on different webserver configuration. Some methods may not work at all. – Flash Thunder Feb 10 '15 at 13:17
  • Where does `$someData` come from? Do you want to return something from your async call? – Jon Surrell Feb 10 '15 at 13:18
  • `$someData` is calculated before the `$this->slowMethod()`, I proposed to my client to divide this methode in 2, and make 2 request one for the first method and the second for the the other method, but it told me to find a solution only in backoffice – Alexandru Olaru Feb 10 '15 at 13:22

2 Answers2

3

You cannot execute a method asynchronously. But you could return the data to the client, close the connection, and execute your time consuming method once you disconnected.

This answer goes in details.

Another solution to execute php code asynchronously is forking a new process with pclose(popen()).

Or for a really advanced solution you could look into the threading module of PHP.

Community
  • 1
  • 1
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
1

You may use threads: PHP threading call to a php function asynchronously

This is quite only way to do so. there is several ways of using them, so choice the best/easiest for you.

Im using this normally: http://php.net/manual/en/class.thread.php

Community
  • 1
  • 1
Seti
  • 2,169
  • 16
  • 26
  • Thought about it but it requires to compilate the PHP in specific way, `pthreads requires a build of PHP with ZTS (Zend Thread Safety)` do not have the luxury to do that. – Alexandru Olaru Feb 10 '15 at 13:17
  • Then you may use DB. Add the data you want to table (id, data, request,anything, flag) . Then set cronjob. If flag is set to `not done`, then in cron job finish the job and set the flag to `done`. This maybe isnt async, but it moves the semi-workthred from the user request to server side. And then, you may add some easy ajax PINGs with the `delayed` request id, so user can check whenever its finished and receive it. – Seti Feb 10 '15 at 16:02